使用JDBC操作数据库基本操作步骤

发布时间 2023-10-19 13:14:44作者: 熬夜就犯困
  1. 书写jdbc需要四大要素:用户名、密码、URL、驱动
String url = "jdbc:mysql://localhost:3306/test"; 
String username = "root";
String password = "root";
String driver = "com.mysql.jdbc.Driver";
  1. 注册驱动
Class.forName(driver);
  1. 获取连接对象
Connection conn = DriverManager.getConnection(url , username , password ) ; 
  1. 编写动态sql语句(防止sql注入)
String sql = "select username from user where age > ?";
/*
String sql = "update user set username = ? where username = ?"
*/
  1. 获取PreParedStatement对象
PreparedStatement pstmt = con.prepareStatement(sql) ;
  1. 注入参数
pstmt.setInt(1,18);
/*
pstmt.setString(1,"张三");
pstmt.setString(2,"李四");
*/
  1. 获取结果
ResultSet rs = pstmt.executeqQuery();
while(rs.next()) {
   String username =  rs.getString("username");
    System.out.println(username);
}
/*
int count = pstmt.executeUpdate();
if(count > 0) {
    System.out.pirntln("执行成功...");
} else{

    System.out.println("执行失败...");
}

*/
  1. 关闭资源
if(rs !=null){   // 关闭记录集
    try {
       rs.close();
    } catch (SQLException e) {
       e.printStackTrace();   
    }
}

if(pstmt !=null){   // 关闭声明
    try {
       pstmt.close();
    } catch (SQLException e) {
       e.printStackTrace();
    }
}

if(conn !=null){  // 关闭连接对象
    try {
       conn.close();
     } catch (SQLException e) {
        e.printStackTrace();   
     }
}

总结

  1. 定义四大元素
  2. 注册驱动
  3. 获取连接对象
  4. 获取PreparedStatement对象
  5. 参数注入
  6. 获取ResultSet对象
  7. 获取执行结果
  8. 关闭资源

当执行增删改的时候调用executeUpdate方法,查询则调用executeQuery方法...