Guest User

Untitled

a guest
Apr 26th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import java.sql.DriverManager;
  2. import java.sql.ResultSet;
  3. import java.sql.SQLException;
  4.  
  5. import com.mysql.jdbc.Connection;
  6. import com.mysql.jdbc.Statement;
  7.  
  8. public class SqlClass {
  9.  
  10. public static final String url = "jdbc:Mysql://localhost:3306/zichenDB?characterEncoding=utf8&useSSL=true";
  11. public static final String name = "com.mysql.jdbc.Driver";
  12. public static final String user = "root";
  13. public static final String password = "admin123456";
  14.  
  15. static Connection con;
  16. String sql;
  17.  
  18. public void SqlClassTest() throws ClassNotFoundException {
  19. System.out.println("----------------------------------\n");
  20. System.out.println("hello, sql -- class");
  21.  
  22. try {
  23. Class.forName(name);
  24. con = (Connection) DriverManager.getConnection(url, user, password);
  25. if(!con.isClosed()) {
  26. System.out.println("connection success");
  27.  
  28. Statement sqlMent = (Statement) con.createStatement();
  29. // 同名数据库, 删除
  30. sqlMent.executeUpdate("drop table if exists orderStaff");
  31. sql = "create table orderStaff(orderId int not null, name varchar(20), orderDesc varchar(32), primary key(orderId))";
  32. int result = sqlMent.executeUpdate(sql);
  33. if(result == -1) {
  34. System.out.println("创建失败");
  35. }
  36.  
  37. // 插入数据库
  38. sqlMent.executeUpdate("insert orderStaff values(1, 'zichen01', 'zichen00001')");
  39. sqlMent.executeUpdate("insert orderStaff values(2, 'zichen02', 'zichen00002')");
  40. sqlMent.executeUpdate("insert orderStaff values(3, 'zichen03', 'zichen00003')");
  41.  
  42. // 执行查询数据
  43. String query = "select * from orderStaff";
  44. ResultSet ret = sqlMent.executeQuery(query);
  45. System.out.println("orderStaff 表中得数据如下:");
  46. System.out.println("------------------------");
  47. while(ret.next()) {
  48. int orderId = ret.getInt("orderId");
  49. String name = ret.getString("name");
  50. String desc = ret.getString("orderDesc");
  51. // 取得数据库中的数据
  52. System.out.println("id:" + orderId + " name:"+name + " desc:"+desc);
  53. }
  54. sqlMent.close();
  55. con.close();
  56. }
  57. } catch (SQLException e) {
  58. e.printStackTrace();
  59. }
  60.  
  61. System.out.println("----------------------------------\n");
  62. }
  63. }
Add Comment
Please, Sign In to add comment