Guest User

Untitled

a guest
Jan 19th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. package com.example;
  2.  
  3. import java.io.PrintWriter;
  4. import java.sql.*;
  5.  
  6. public class JDBCDemo {
  7. public static void main(String[] args) throws ClassNotFoundException, SQLException {
  8. // 1. 要连接的数据库url
  9. String url = "jdbc:mysql://localhost:3306/jdbcStudy";
  10.  
  11. // 连接数据库要使用的用户名
  12. String username = "root";
  13.  
  14. // 连接数据库要使用的密码
  15. String password = "8887447235";
  16.  
  17. // 2. 加载驱动
  18. //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 不推荐使用这种方式
  19. Class.forName("com.mysql.jdbc.Driver"); // 使用反射机制加载
  20.  
  21. // 3. 获取与数据库的连接
  22. Connection con = DriverManager.getConnection(url, username, password);
  23.  
  24. // 4. 获取向数据库发送sql语句的statement
  25. Statement st = con.createStatement();
  26.  
  27. // sql语句
  28. String sql = "select id,name,password,email,birthday from users";
  29.  
  30. // 5. 向数据发送sql语句
  31. ResultSet set = st.executeQuery(sql);
  32.  
  33.  
  34. // 6. 取出结果集数据
  35. while (set.next()){
  36. System.out.println("id=" + set.getObject("id"));
  37. System.out.println("name=" + set.getObject("name"));
  38. System.out.println("password=" + set.getObject("password"));
  39. System.out.println("email=" + set.getObject("email"));
  40. System.out.println("birthday=" + set.getObject("birthday"));
  41. }
  42.  
  43. // 7. 关闭连接释放资源
  44. set.close();
  45. st.close();
  46. con.close();
  47.  
  48. }
  49. }
Add Comment
Please, Sign In to add comment