Guest User

Untitled

a guest
Nov 21st, 2017
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. package test;
  2.  
  3. import java.sql.*;
  4.  
  5. public class test { // 下面定义一些全局静态参数,用于数据库连接
  6.  
  7. static final String driver = "com.mysql.jdbc.Driver";
  8. static final String url = "jdbc:mysql://localhost:3306/test";
  9. static final String user = "root";
  10. static final String password = "hello";
  11.  
  12. public static void main(String[] args) throws SQLException {
  13.  
  14. Connection con = null; //创建一个连接对象
  15. Statement stmt = null; //创建一个语句对象
  16. ResultSet rs = null;
  17.  
  18. try {
  19. Class.forName(driver);
  20. con = DriverManager.getConnection(url, user, password); //连接数据库
  21. con.setAutoCommit(false); // 关掉自动事务递交
  22.  
  23. stmt = con.createStatement(); //初始化语句
  24.  
  25. String query1 = "update test1 set name ='Shanghai' where id >100";
  26. String query2 = "update test1 set name ='Beijing' where id >50 and id <90";
  27. String query3 = "select * from test1 where id >50";
  28.  
  29. stmt.executeUpdate(query1);
  30. stmt.executeUpdate(query2);
  31. rs = stmt.executeQuery(query3);
  32.  
  33. con.commit();
  34.  
  35. System.out.println("-----------------");
  36. System.out.println("执行结果如下所示:");
  37. System.out.println("-----------------");
  38. String uid = null;
  39. String name = null;
  40.  
  41. while (rs.next()) {
  42. //获取stuname这列数据
  43. uid = rs.getString("id");
  44. //获取stuid这列数据
  45. name = rs.getString("name");
  46. //输出结果
  47. System.out.println(uid + "\t" + name);
  48. }
  49. rs.close(); //关语句
  50. con.close(); //关连接
  51. } catch (ClassNotFoundException e) {//如果 JDBC class 找不到捕获抛异常
  52. //数据库驱动类异常处理
  53. System.out.println("找不到数据库驱动");
  54. e.printStackTrace();
  55. } catch (SQLException e) { // JDBC 层工作中有问题抛异常
  56. System.err.println("无法连接到数据库");
  57. e.printStackTrace();
  58. } catch (Exception e) { // 执行操作有问题抛异常
  59. con.rollback(); // 失败执行事务回滚
  60. e.printStackTrace();
  61. } finally {
  62. System.out.println("关闭连接");
  63. if (con !=null) try {con.close(); } catch (SQLException ignore) {} //关闭不掉链接就抛异常
  64. }
  65. }
  66.  
  67. }
Add Comment
Please, Sign In to add comment