是什么?

JDBC:Java Data Base Connectivity(java数据库连接)

为什么用?

sun公司提供JDBC API接口,数据库厂商来提供实现

我们需要用哪个数据库就加载那个数据库厂商提供的驱动包

怎么用?

需要先在数据库中建立表

我的数据库名为db_user,表名为t_user

  1. package com.zhangwei.test;
  2. import java.sql.*;
  3. public class DBTest {
  4. public static void main(String[] args) {
  5. Connection connection = null;
  6. Statement statement = null;
  7. ResultSet resultSet = null;
  8. try {
  9. Class.forName("com.mysql.jdbc.Driver");
  10. connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_user?useSSL=false", "root", "123456");
    //黄色部分为 需要显式禁用SSL设置usessl = false,或设置usessl =true提供服务器证书验证信任库。
  11. statement = connection.createStatement();
  12. resultSet = statement.executeQuery("SELECT * FROM t_user");
  13. while(resultSet.next()){
  14. System.out.println(resultSet.getInt(1));
  15. System.out.println(resultSet.getString(2));
  16. System.out.println(resultSet.getString(3));
  17. System.out.println(resultSet.getString(4));
  18. }
  19. }catch (SQLException e){
  20. e.printStackTrace();
  21. }catch (ClassNotFoundException e){
  22. e.printStackTrace();
  23. }finally{
  24. if(resultSet != null){
  25. try {
  26. resultSet.close();
  27. } catch (SQLException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. if(statement != null){
  32. try {
  33. statement.close();
  34. } catch (SQLException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. if(connection != null){
  39. try {
  40. connection.close();
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
  46. }
  47. }

运行结果:

需要知道的几个对象

Connection对象:客户端与数据库的交互(DriverManager.getConnection()时返回此对象)

Statement对象:用于向数据库发送Sql语句,实现数据库的增删改查(connection.createStatement()时返回此对象)

Resultset对象:代表SQL语句的执行结果(statement.executeQuery()时返回此对象)

转载自:https://segmentfault.com/a/1190000013293202

 

版权声明:本文为zdjsproxy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zdjsproxy/p/10158501.html