JDBC编程步骤

1.注册驱动

Class.forname("com.mysql.jdbc.Driver");

2.获取链接

Connection con=DriverManager.getConnection(url,user,password);

3.创建statement对象

Statement st=con.createment();

4.发送sql并且执行

ResultSet rs=st.executeQuery();

5.遍历结果集

while(rs.next){

  ...

}

6.释放资源,放在finally中

案例:

public static void main(String[] args) {
        
        //获取连接
        Connection con = null;
        //创建statement对象
        Statement statement = null;
        ResultSet rs = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/day09", "root", "123");
            statement = con.createStatement();
            //发送并执行sql
            String sql = "select * from user";
            rs = statement.executeQuery(sql);
            //遍历
            while(rs.next()){
                String id = rs.getString("id");
                String name = rs.getString(2);
                int age = rs.getInt(3);
                System.out.println(id+"+++"+name+"++++"+age);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            //释放资源
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/lichangyun/p/8643259.html