1.什么是JDBC?

在看JDBC的概念之前先来看看什么是数据库驱动。

数据库驱动中驱动的概念和平时听到的那种驱动的概念是一样的,比如平时购买的声卡,网卡直接插到计算机上面是不能用的,必须要安装相应的驱动程序之后才能够使用声卡和网卡,同样道理,我们安装好数据库之后,我们的应用程序也是不能直接使用数据库的,必须要通过相应的数据库驱动程序,通过驱动程序去和数据库打交道。

SUN公司为了简化、统一对数据库的操作,定义了一套Java操作数据库的规范(接口),称之为JDBC(Java Data Base Connectivity)。这套接口由数据库厂商去实现,这样,开发人员只需要学习jdbc接口,并通过jdbc加载具体的驱动,就可以操作数据库。

综上,JDBC是一个独立于特定数据库管理系统、通用的SQL数据库存取和操作的公共接口,定义了用来访问数据库的标准java类库,使用这个类库可以以一种标准的方法方便地访问数据库资源。JDBC的目标是使程序员使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统,这样使得程序员无需对特定的数据库系统的特点有过多的了解,从而大大简化和加快了开发过程。

2.JDBC API

JDBC API是一系列的接口,它使得应用程序能够进行数据库连接,执行SQL语句,并且得到返回结果。数据库厂商使用的Java.sql.Driver接口是所有JDBC驱动程序需要实现的接口,在java程序中不需要直接去访问实现了Driver接口的类,而是由驱动程序管理器类java.sql.DriverManager去调用这些Driver实现。

3.JDBC获取数据库的连接

3.1 使用Driver接口获取数据库的连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.test.jdbc;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;
 
import org.junit.Test;
/*
 * 编写一个通用的方法,在不修改源程序的条件下,可以获取任何数据库的连接
 * */
 
public class JDBCTest {
    public Connection getConnection() throws Exception{<br>                //准备连接数据库的4个字符串
        String driverClass=null;
        String jdbcUrl=null;
        String user=null;
        String password=null;
        //获取类路径下的jdbc.properties文件
        InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties=new Properties();
        properties.load(in);
        //读取properties文件内容
        driverClass=properties.getProperty("driver");
        jdbcUrl=properties.getProperty("jdbcUrl");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
        //通过反射创建java对象
        Driver driver=(Driver)Class.forName(driverClass).newInstance();
        Properties info=new Properties();
        info.put("user",user);
        info.put("password",password);
        Connection connection=driver.connect(jdbcUrl, info);
         
        return connection;
    }
    @Test
    public void testGetConnection() throws Exception{
        System.out.println(getConnection());
    }
}

jdbc.properties

1
2
3
4
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3303/extra
user=root
password=0404

3.2 使用DriverManager类获取数据库连接

通过DriverManager连接数据库的基本步骤分为:

①准备连接数据库的4个字符串,driverClass,jdbcUrl,user,password;

1).获取类路径下的jdbc.properties文件

2).读取properties文件内容,获取4个字符串的值

②加载数据库驱动程序;

③通过DriverManager的getConnection()方法获取数据库连接;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.test.jdbc;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
 
public class JDBCTest {   
     
    public Connection getConnection() throws Exception{
        //1.准备连接数据库的4个字符串
        String driverClass=null;
        String jdbcUrl=null;
        String user=null;
        String password=null;
        //获取类路径下的jdbc.properties文件
        InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties=new Properties();
        properties.load(in);
        //读取properties文件内容
        driverClass=properties.getProperty("driver");
        jdbcUrl=properties.getProperty("jdbcUrl");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
        //2.加载数据库驱动程序
        Class.forName(driverClass);
        //3.通过DriverManager的getConnection()方法获取数据库连接
        Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
        return connection;
    }
    @Test
    public void testGetConnection() throws Exception{
        System.out.println(getConnection());
    }
}

使用DriverManager可以注册多个驱动程序,从而使得使用多个jdbcUrl可以连接不同的数据库。

4.通过Statement执行更新操作

Statement是用于执行SQL语句的对象:

①通过Connection的createStament()方法来获取;

②通过executeUpdate(sql)可以执行SQL语句;

③传入的SQL可以是INSERT,UPDATE或DELETE,但不能是SELECT;

④关闭的顺序是先关闭后获取的,即先关闭statement,再关闭connection;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.test.jdbc;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;
 
/**
 * @author Administrator
 *
 */
public class JDBCTest {
    @Test
    public void testStatement() throws Exception{
        Connection con=null;
        Statement statement=null;
        try{
            //1.获取数据库连接
            con=getConnection();
            //2.准备插入的SQL连接
            String sql="INSERT INTO TEST VALUES(NULL,'B','bdbs.@koala.com','2018-8-09')";
            //3.执行插入
            //1).获取操作SQL语句的Statement对象,调用Connection的createStatement()方法来获取;
            statement=con.createStatement();
            //2).调用Statement对象的executeUpdate(sql)执行SQL语句进行插入
            statement.executeUpdate(sql);
        }catch(Exception e){
            e.printStackTrace();
            }finally{
                //使用try...catch...是为了确保出现异常也能关闭数据库。
                //4.关闭Statement对象
                try {
                    if(statement!=null)
                    statement.close();
                catch (SQLException e) {
                    e.printStackTrace();
                }finally{
                    //5.关闭数据库连接
                    if(con!=null)
                    con.close();
                }
        }
    }
    public Connection getConnection() throws Exception{
        //1.准备连接数据库的4个字符串
        String driverClass=null;
        String jdbcUrl=null;
        String user=null;
        String password=null;
        //获取类路径下的jdbc.properties文件
        InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties=new Properties();
        properties.load(in);
        //读取properties文件内容
        driverClass=properties.getProperty("driver");
        jdbcUrl=properties.getProperty("jdbcUrl");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
        //2.加载数据库驱动程序
        Class.forName(driverClass);
        //3.通过DriverManager的getConnection()方法获取数据库连接
        Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
        return connection;
    }
    @Test
    public void testGetConnection() throws Exception{
        System.out.println(getConnection());
    }
}

5.一个通用的更新数据库的方法,包括INSERT,UPDATE,DELETE。

首先将数据库的连接和释放的方法封装到工具类中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.test.jdbc;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.junit.Test;
/*
 * 操作JDBC的工具类,其中封装了一些工具方法。
 */
public class JDBCTools {
    //获取连接的方法
    public static Connection getConnection() throws Exception{
        //1.准备连接数据库的4个字符串
        String driverClass=null;
        String jdbcUrl=null;
        String user=null;
        String password=null;
        //获取类路径下的jdbc.properties文件
        InputStream in=JDBCTools.class.getResourceAsStream("jdbc.properties");
        Properties properties=new Properties();
        properties.load(in);
        //读取properties文件内容
        driverClass=properties.getProperty("driver");
        jdbcUrl=properties.getProperty("jdbcUrl");
        user=properties.getProperty("user");
        password=properties.getProperty("password");
        //2.加载数据库驱动程序
        Class.forName(driverClass);
        //3.通过DriverManager的getConnection()方法获取数据库连接
        Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
        return connection;
    }
    @Test
    public void testGetConnection() throws Exception{
        System.out.println(getConnection());
    }
    //释放连接的方法
    public static void release(Statement statement,Connection connection){
        //使用try...catch...是为了确保出现异常也能关闭数据库。
        //4.关闭Statement对象
        if(statement!=null){
        try {
            statement.close();
        catch (SQLException e) {
            e.printStackTrace();
        }
        }
        if(connection!=null){
        try {
            //5.关闭数据库连接
            connection.close();
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
    }
}

通用的更新方法,包括INSERT,UPDATE,DELETE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.test.jdbc;
 
import java.sql.Connection;
import java.sql.Statement;
import org.junit.Test;
import com.test.jdbc.JDBCTools;
 
public class JDBCTest {
    public void update(String sql){
        Connection con=null;
        Statement statement=null;
        try{
            con=JDBCTools.getConnection();
            statement=con.createStatement();
            statement.executeUpdate(sql);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JDBCTools.release(statement, con);
        }
    }
}

6.通过ResultSet执行查询操作

ResultSet结果集,封装了使用JDBC进行查询的结果。

①调用Statement对象的executeQuery(sql)可以得到结果集;

②ResultSet返回的实际上是一张数据表,有一个指针指向数据表的第一行的前面。可以调用next()方法检测下一行是否有效,若有效该方法返回true,且指针下移,相当于Iterator对象的hasNext()和next()方法的结合体;

③当指针对位到一行时,可以通过getXxx(index)或getXxx(columnName)获取每一列的值,例如:getInt(1),getString("name");

④ResultSet也需要关闭。

数据表如下,获取所有信息并打印。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.test.jdbc;
 
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.test.jdbc.JDBCTools;
 
public class JDBCTest {
    @Test
    public void testResultSet() throws Exception{
        //1.获取connection
        Connection con=null;
        Statement statement=null;
        ResultSet resultset=null;
        try{
            JDBCTools tool=new JDBCTools();
            con=tool.getConnection();
            //2.获取statement
            statement=con.createStatement();
            //3.准备SQL
            String sql="SELECT ID,NAME,EMAIL,BIRTH FROM TEST";
            //4.执行查询,得到resultset
            resultset=statement.executeQuery(sql);
            //5.处理ResultSet
            while(resultset.next()){
                int ID=Integer.parseInt(resultset.getString(1));
                String NAME=resultset.getString("NAME");
                String EMAIL=resultset.getString(3);
                Date date=resultset.getDate(4);
                 
                System.out.println(ID);
                System.out.println(NAME);
                System.out.println(EMAIL);
                System.out.println(date);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //6.关闭数据库资源
            JDBCTools.release(statement,con,resultset);
        }
    }
}
    

运行结果:

https://www.cnblogs.com/naihuangbao/p/10055211.html

JDBC数据库基本操作的更多相关文章

  1. ecmall数据库基本操作

    ecmall数据库基本操作,为了认真研究ecmall二次开发,我们必须熟悉ecamll的数据库结构,ecmall数据库结构研究熟悉之后,才能去认真分析ecamll的程序结构.从而实现ecmall二次开 ...

  2. Oracle 数据库基本操作——实用手册、表操作、事务操作、序列

    目录: 0. 参考链接与参考手册1. oracle 实用(常用操作)指令2. 数据库基本操作语法 a) 表操作 1)创建表 2)更新表 3)删除表 4)查询 b) 事务操作 c) 序列操作 1)创建序 ...

  3. MySQL系列:数据库基本操作(1)

    1. 登录数据库 mysql -h localhost -u root -p 2. 数据库基本操作 2.1 查看数据库 mysql> SHOW DATABASES; +------------- ...

  4. MySQL 5.6学习笔记(数据库基本操作,查看和修改表的存储引擎)

    1. 数据库基本操作 1.1  查看数据库 查看数据库列表: mysql> show databases; +--------------------+ | Database | +------ ...

  5. Oracle数据库基本操作(一) —— Oracle数据库体系结构介绍、DDL、DCL、DML

    一.Oracle数据库介绍 1.基本介绍 Oracle数据库系统是美国ORACLE公司(甲骨文)提供的以分布式数据库为核心的一组软件产品,是目前最流行的客户/服务器(CLIENT/SERVER)或B/ ...

  6. (三)mysql数据库基本操作

    (1)SQL语句:结构化查询语句 DDL语句 数据定义语言:数据库丶表丶视图丶索引丶存储过程丶函数丶create drop alter DML语句 数据库操作语言:插入数据insert,删除数据del ...

  7. activemq 5.13.2 jdbc 数据库持久化 异常 找不到驱动程序

    原文:https://my.oschina.net/u/2284972/blog/662033 摘要: activemq jdbc 数据库持久化 异常 找不到驱动程序 Caused by: java. ...

  8. laravel基础课程---13、数据库基本操作2(lavarel数据库操作和tp对比)

    laravel基础课程---13.数据库基本操作2(lavarel数据库操作和tp对比) 一.总结 一句话总结: 非常非常接近:也是分为两大类,原生SQL 和 数据库链式操作 学习方法:使用时 多看手 ...

  9. laravel基础课程---10、数据库基本操作(如何使用数据库)

    laravel基础课程---10.数据库基本操作(如何使用数据库) 一.总结 一句话总结: 1.链接数据库:.env环境配置里面 2.执行数据库操作:DB::table('users')->up ...

随机推荐

  1. java基础篇---内存分析

    Java的并发采用的是共享内存模型(而非消息传递模型),线程之间共享程序的公共状态,线程之间通过写-读内存中的公共状态来隐式进行通信.多个线程之间是不能直接传递数据交互的,它们之间的交互只能通过共享变 ...

  2. spring websocket + stomp 实现广播通信和一对一通信<转>

    spring对于基于stomp协议的websocket通信,其官网上面有一个guide,但是根据guide你只能写出来广播方式的通信,不能实现一对一的通信,这篇文章在这里把广播和一对一一起整理一下给大 ...

  3. Mongodb网络好文章

    http://blog.csdn.net/pi9nc/article/details/17722419 mongodb集群配置. http://blog.fens.me/mongodb-replica ...

  4. Bash Shell (十一)

    [教程主题]:Bash Shell [课程录制]: 创E [主要内容] [1] Hello World! 几乎所有的讲解编程的书给读者的第一个例子都是 Hello World 程序,那么我们今天也就从 ...

  5. 【html5】html5 本地存储

    最近一直在学习 html5,为了后期的移动项目进行知识储备.html5 相对于 html4 新增加了一些有趣的标签.属性和方法,今天主要介绍下 html5 的本地存储. 在客户端存储数据 html5 ...

  6. 谷歌draco

    前不久,谷歌开源的Draco关于点云的编码与压缩的源码,Draco 由谷歌 Chrome 媒体团队设计,旨在大幅加速 3D 数据的编码.传输和解码.因为研发团队的 Chrome 背景,这个开源算法的首 ...

  7. redis连接超时问题排查

    连接池无法获取到连接或获取连接超时redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource f ...

  8. Linux source命令

    Linux source命令   Linux source命令: 通常用法:source filepath 或 . filepath 功能:使当前shell读入路径为filepath的shell文件并 ...

  9. 如何安装Node.js环境

    一.在Windows系统下安装Node.js环境 1. 下载地址:官网http://nodejs.org/ 2.   安装nodejs,根据自己情况,安装路径 D:\Program Files\nod ...

  10. python的callback函数原理

    __getattribute__作用 """ class C(object): a = 'abc' def __getattribute__(self, *args, * ...