JDBC入门程序详解

什么是JDBC

 JDBC的英文全称是"Java Database Connectivity",根据英文的意思就是Java数据库连接。是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。在下面的演示中会提到一些。
 

环境准备

我们需要什么?

  • 编译环境:Intelli IDEA
  • 数据库:Mysql 5.7.28
  • Mysql驱动包:mysql-connector-java-5.1.39-bin.jar

驱动包下载地址:https://pan.baidu.com/s/1IeI1r2wFjaxQntu7kS09iA
密码: u086

驱动包安装步骤

1.在项目下新建一个lib文件夹,并将刚刚下载好的mysql-connector-java-5.1.39-bin.jar驱动包粘贴至这个文件夹下。在这里插入图片描述
2.右键单击,找到Add as Library单击后选择ok(在Eclipse中不是直接Add as Library,而是Build Path)
在这里插入图片描述
3.选择ok后就可以看到jar包目录下出现了新的文件,说明我们已经导入成功了。在这里插入图片描述

数据库准备

建立表格并准备一些数据
在这里插入图片描述
在这里插入图片描述
 

开始编写!

主要步骤

  • 加载驱动
  • 获得连接
  • 获得执行SQL语句的对象
  • 编写SQL语句
  • 执行SQL
  • 遍历结果集(案例中使用的是select,所以会有结果集)
  • 释放资源

步骤详解

 先创建一个名为JDBCDemo1的类,在类中新建一个demo1方法,记得在方法前写上@TEST,这样我们就可以单独测试类中的一个方法,不必再去重新写一个main函数。
 
1.加载驱动

 Class.forName("com.mysql.jdbc.Driver");//加载驱动

Class.forName():将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static代码块。
 
2.获得连接

Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/web_test3?useSSL=false", "root", "Zjy9201141217");

我们来看一下getConnection方法的源码

 @CallerSensitive
    public static Connection getConnection(String url,
        String user, String password) throws SQLException {
        java.util.Properties info = new java.util.Properties();

        if (user != null) {
            info.put("user", user);
        }
        if (password != null) {
            info.put("password", password);
        }

        return (getConnection(url, info, Reflection.getCallerClass()));//再次调用了另一个getConnection方法
    }

这里我们会传三个参数(url,user,password)进入到getConnection这个方法中。

  • url:Mysql的url就是 jdbc:mysql://hostname:port/database,部分用户可能需要加上useSSL=false这个参数,有可能会出现下面这个错误:

Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+,5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
原因是MySQL在高版本需要指明是否进行SSL连接。

  • user:Mysql数据库的用户名,没改过的话一般是root
  • password:Mysql数据库的密码,自己记住
    在这个方法中,最后会返回另一个getConnection,在info中以键值对的方式储存user和password,再传输到另一个getConnection,至于下面的代码本人能力有限,暂时无法详细解释😖😖😖
//  Worker method called by the public getConnection() methods.
    private static Connection getConnection(
        String url, java.util.Properties info, Class<?> caller) throws SQLException {
        /*
         * When callerCl is null, we should check the application's
         * (which is invoking this class indirectly)
         * classloader, so that the JDBC driver class outside rt.jar
         * can be loaded from here.
         */
        ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
        if (callerCL == null || callerCL == ClassLoader.getPlatformClassLoader()) {
            callerCL = Thread.currentThread().getContextClassLoader();
        }

        if (url == null) {
            throw new SQLException("The url cannot be null", "08001");
        }

        println("DriverManager.getConnection(\"" + url + "\")");

        ensureDriversInitialized();

        // Walk through the loaded registeredDrivers attempting to make a connection.
        // Remember the first exception that gets raised so we can reraise it.
        SQLException reason = null;

        for (DriverInfo aDriver : registeredDrivers) {
            // If the caller does not have permission to load the driver then
            // skip it.
            if (isDriverAllowed(aDriver.driver, callerCL)) {
                try {
                    println("    trying " + aDriver.driver.getClass().getName());
                    Connection con = aDriver.driver.connect(url, info);
                    if (con != null) {
                        // Success!
                        println("getConnection returning " + aDriver.driver.getClass().getName());
                        return (con);
                    }
                } catch (SQLException ex) {
                    if (reason == null) {
                        reason = ex;
                    }
                }

            } else {
                println("    skipping: " + aDriver.driver.getClass().getName());
            }

        }

        // if we got here nobody could connect.
        if (reason != null)    {
            println("getConnection failed: " + reason);
            throw reason;
        }

        println("getConnection: no suitable driver found for "+ url);
        throw new SQLException("No suitable driver found for "+ url, "08001");
    }
}

3.基本操作:执行SQL

//3.1获得执行SQL语句的对象
Statement statement = conn.createStatement();
//3.2编写SQL语句
String sql="select * from user";
//3.3执行SQL
ResultSet rs = statement.executeQuery(sql);
 //3.4遍历结果集
while(rs.next()) {
	System.out.print(rs.getInt("id")+" ");
    System.out.print(rs.getString("username")+" ");
    System.out.print(rs.getString("nickname")+" ");
    System.out.print(rs.getString("password")+" ");
    System.out.print(rs.getInt("age"));
    System.out.println();
}

为什么要先获取执行SQL语句的对象,让这个Statement去执行SQL语句呢?可以这样想:Connection conn=DriverManager.getConnection(...)相当于出现了一位皇帝,皇帝想要发布一道圣旨,你见过皇帝亲自读圣旨的吗?所以这时候Statement statement = conn.createStatement();出现了,皇帝(conn)封了一位钦差大臣(statement),并写了一道圣旨:String sql="select * from user";然后钦差大臣就拿着这个圣旨(sql)去指定的地方读并生效:ResultSet rs = statement.executeQuery(sql);然后这个圣旨就开始生效了。
 
这里说一下ResultSet,它就是刚刚说的结果集,用于存放通过执行"select * from user"得到的数据。那rs.next()是什么意思?

 boolean next() throws SQLException;

这里可以看到next()方法是boolean类型的,所以在执行rs.next()方法时,它用于判断结果集是否还有下一个记录,有则返回true,没有则返回false。

那么rs.getInt("id")rs.getString("username")又是什么呢?这个根据你建立的数据库来调用方法。比如下图中的Field的值是id,Type是int,所以要获取这个字段的值就需要rs.getInt("id")在这里插入图片描述
4.释放资源

//4.释放资源
 	rs.close();
    statement.close();
    conn.close();

在这里插入图片描述
(来源于https://www.cnblogs.com/yikuan-919/p/9509071.html)
 

完整代码与实现结果

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * JDBC入门程序
 * @author zhengjunyuan
 *
 */

public class JDBCDemo1 {
    @Test
    public void demo1() throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2.获得连接
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/web_test3?useSSL=false", "root", "Zjy9201141217");

        //3.基本操作:执行SQL

        //3.1获得执行SQL语句的对象
        Statement statement = conn.createStatement();
        //3.2编写SQL语句
        String sql="select * from user";
        //3.3执行SQL
        ResultSet rs = statement.executeQuery(sql);

        //3.4遍历结果集
        while(rs.next()) {
            System.out.print(rs.getInt("id")+" ");
            System.out.print(rs.getString("username")+" ");
            System.out.print(rs.getString("nickname")+" ");
            System.out.print(rs.getString("password")+" ");
            System.out.print(rs.getInt("age"));
            System.out.println();
        }

        //4.释放资源
        rs.close();
        statement.close();
        conn.close();
    }

}

在这里插入图片描述

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Noah Blake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值