- 书写jdbc需要四大要素:用户名、密码、URL、驱动
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
String driver = "com.mysql.jdbc.Driver";
- 注册驱动
Class.forName(driver);
- 获取连接对象
Connection conn = DriverManager.getConnection(url , username , password ) ;
- 编写动态sql语句(防止sql注入)
String sql = "select username from user where age > ?";
/*
String sql = "update user set username = ? where username = ?"
*/
- 获取PreParedStatement对象
PreparedStatement pstmt = con.prepareStatement(sql) ;
- 注入参数
pstmt.setInt(1,18);
/*
pstmt.setString(1,"张三");
pstmt.setString(2,"李四");
*/
- 获取结果
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("执行失败...");
}
*/
- 关闭资源
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();
}
}
总结
- 定义四大元素
- 注册驱动
- 获取连接对象
- 获取PreparedStatement对象
- 参数注入
- 获取ResultSet对象
- 获取执行结果
- 关闭资源
标签:username,JDBC,String,rs,数据库,获取,sql,操作步骤,pstmt From: https://www.cnblogs.com/zysstart/p/17774475.html当执行增删改的时候调用executeUpdate方法,查询则调用executeQuery方法...