JDBC使用模板

柔情只为你懂 2022-10-16 00:46 222阅读 0赞

JDBC使用模板

  1. //1.导入驱动jar包
  2. //2.注册驱动
  3. Class.forName("com.mysql.jdbc.Driver");
  4. //3.获取数据库连接对象
  5. Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "123456");
  6. //4.定义sql语句
  7. String sql = "update user set username = 'qiqi' where userId = 1";
  8. //5.获取执行sql的对象 Statement
  9. Statement stmt = conn.createStatement();
  10. //6.执行sql
  11. int count = stmt.executeUpdate(sql);
  12. //7.处理结果
  13. System.out.println(count);
  14. //8.释放资源
  15. stmt.close();
  16. conn.close();
  17. public static void main(String[] args) {
  18. Connection conn = null;
  19. Statement stmt = null;
  20. try {
  21. //1.导入驱动jar包
  22. //2.注册驱动
  23. Class.forName("com.mysql.jdbc.Driver");
  24. //3.获取数据库连接对象
  25. conn = DriverManager.getConnection("jdbc:mysql:///school", "root", "123456");
  26. //4.定义sql语句
  27. String sql1 = "update user set username = 'zhier' where userId = 2";
  28. String sql2 = "Insert into user(userId,username,password) values (3,'sansan','123456')";
  29. String sql3 = "delete from user where userId = 3";
  30. //5.获取执行sql的对象 Statement
  31. stmt = conn.createStatement();
  32. //6.执行sql
  33. int i = stmt.executeUpdate(sql3);
  34. //7.处理结果
  35. System.out.println(i);
  36. } catch (ClassNotFoundException e) {
  37. e.printStackTrace();
  38. } catch (SQLException throwables) {
  39. throwables.printStackTrace();
  40. }finally {
  41. //8.释放资源
  42. // stmt.close();
  43. // conn.close()
  44. if (stmt != null){
  45. try {
  46. stmt.close();
  47. } catch (SQLException throwables) {
  48. throwables.printStackTrace();
  49. }
  50. }
  51. if (conn != null){
  52. try {
  53. conn.close();
  54. } catch (SQLException throwables) {
  55. throwables.printStackTrace();
  56. }
  57. }
  58. }
  59. }

发表评论

表情:
评论列表 (有 0 条评论,222人围观)

还没有评论,来说两句吧...

相关阅读