• JDBC数据库基本操作


    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

  • 相关阅读:
    【C++】虚函数
    ZF-net
    bzoj1061【NOI2008】志愿者招募
    highcharts 绘制图标的JAVASCRIPT 类库 收藏
    C语言中的const,free使用方法具体解释
    Java Transaction Management
    从有序数组中查找某个值 low_bound
    [华为机试练习题]35.找零钱
    1.9算法入门之进制转换
    uboot移植rtc
  • 原文地址:https://www.cnblogs.com/sjqq/p/10085308.html
Copyright © 2020-2023  润新知