JDBC获取数据库连接
是什么?
JDBC:Java Data Base Connectivity(java数据库连接)
为什么用?
sun公司提供JDBC API接口,数据库厂商来提供实现
我们需要用哪个数据库就加载那个数据库厂商提供的驱动包
怎么用?
需要先在数据库中建立表
我的数据库名为db_user,表名为t_user
- package com.zhangwei.test;
- import java.sql.*;
- public class DBTest {
- public static void main(String[] args) {
- Connection connection = null;
- Statement statement = null;
- ResultSet resultSet = null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_user?useSSL=false", "root", "123456");
//黄色部分为 需要显式禁用SSL设置usessl = false,或设置usessl =true提供服务器证书验证信任库。- statement = connection.createStatement();
- resultSet = statement.executeQuery("SELECT * FROM t_user");
- while(resultSet.next()){
- System.out.println(resultSet.getInt(1));
- System.out.println(resultSet.getString(2));
- System.out.println(resultSet.getString(3));
- System.out.println(resultSet.getString(4));
- }
- }catch (SQLException e){
- e.printStackTrace();
- }catch (ClassNotFoundException e){
- e.printStackTrace();
- }finally{
- if(resultSet != null){
- try {
- resultSet.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if(statement != null){
- try {
- statement.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if(connection != null){
- try {
- connection.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
运行结果:
需要知道的几个对象
Connection对象:客户端与数据库的交互(DriverManager.getConnection()时返回此对象)
Statement对象:用于向数据库发送Sql语句,实现数据库的增删改查(connection.createStatement()时返回此对象)
Resultset对象:代表SQL语句的执行结果(statement.executeQuery()时返回此对象)
转载自:https://segmentfault.com/a/1190000013293202