操作完整步骤
第一步:准备相关参数
必要参数:数据库链接,用户名,密码
String driverName = "com.mysql.cj.jdbc.Driver";
String dbURL="jdbc:mysql://localhost:3306/users?characterEncoding=utf-8&rewriteBatchedStatement=true";
String userName = "root";
String userPwd = "123456789";
第二步:加载JDBC驱动程序
Class.forName(driverName) ;
第三步:连接数据库
Connection con= DriverManager.getConnection(dbURL, userName, userPwd);
第四步:创建Statement
Statement stmt = con.createStatement();
第五步:执行SQL语句
ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句,返回一个结果集(ResultSet)对象。 int executeUpdate(String sqlString):用于执行INSERT、UPDATE或 DELETE语句以及
String sql;
sql = "delete from users where user_account = 201714350102";
stmt.executeUpdate(sql);
String sql;
sql = "select * from users ";
ResultSet rs = stmt.executeQuery(sql);
第六步:遍历结果集
while(rs.next()){
String id = rs.getString("user_account");
String name = rs.getString("user_name");
String grade = rs.getString("user_grade");
String idenity = rs.getString("user-idenity");
System.out.print("ID:"+id+" ");
System.out.print("name:"+name+" ");
System.out.print("grade:"+grade+" ");
System.out.print("idenity:"+idenity);
System.out.println();
}
第七步:关闭连接
- 先关闭requestSet
- 再关闭Statement
- 最后关闭连接对象connection
rs.close();
stmt.close();
con.close();
|