JDBC的简单使用

package com.fgy.jdbc;

import java.sql.*;

public class Demo1Jdbc {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 1.导入驱动jar包

        // 2.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 3.获取连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root");

        // 4.定义SQL语句
        String sql = "select * from stu";

        // 5.获取statement对象
        // Statement statement = con.createStatement();
        PreparedStatement statement = con.prepareStatement(sql); // 建议使用prepareStatement,可以防止SQL注入

        // 6.执行SQL语句
        // ResultSet rs = statement.executeQuery(sql);
        ResultSet rs = statement.executeQuery();

        // 7.处理结果
        while (rs.next()) {
            System.out.println(rs.getString("name"));
        }

        // 8.释放资源
        statement.close();
        con.close();
    }
}
package com.fgy.jdbc;

import java.sql.*;

public class Demo2Jdbc {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            // 1.导入驱动jar包

            // 2.注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 3.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root");

            // 4.定义SQL语句
            String sql = "insert into stu(name) values ('筱筱')";

            // 5.获取statement对象
            statement = conn.prepareStatement(sql);

            // 6.执行SQL语句
            // statement.execute();
            int i = statement.executeUpdate();
            System.out.println("受影响的行数:" + i);

            // 7.处理结果
            // ...
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 8.释放资源
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/roadlandscape/p/12189478.html