Learning database records Day2 (JDBC)

Day 2

July 6, 2019.
This is my second day learning database.
On this day, I learned the following knowledge.

Introduction to JDBC

JDBC (Java Database Connectivity), SUN company for simplicity, uniform operation of the database, Java specification defines a set of database operations (interface) called JDBC. This set of interfaces to achieve by the database vendors, so developers only have to learn jdbc interface and load the specific driver through jdbc, you can operate the database.
A JDBC java.sql and javax.sql composed of an outer support the development JDBC applications requiring two or more packets, also need to import the appropriate JDBC MySQL Oracle database implementation (i.e., database drivers) .
Here Insert Picture Description

JDBC process

  1. Load the driver
  2. Links for the database
  3. Gets statement used to send sql statements to databases
  4. Sql sent to the database, and get the result set represents the resultset
  5. Remove the result data set
  6. Close links, free up resources

Examples are as follows:

import java.sql.*;

public class test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2.获取与数据库的连接
        String userName = "root";
        String passWord = "123456";
        String url = "jdbc:mysql://localhost:3306/jdbcstudy";

        Connection connection = DriverManager.getConnection(url,userName,passWord);

        //3.编写SQL语句
        String sql = "select id,name,password,email,birthday from users";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);

        //Query : 查询。返回查询到的结果集 ResultSet;
        //Update : 更新,删除,插入,返回受影响的行数

        while (resultSet.next()){
            System.out.println(resultSet.getObject("id"));
            System.out.println(resultSet.getObject("name"));
            System.out.println(resultSet.getObject("password"));
            System.out.println(resultSet.getObject("email"));
        }

        //4.释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}

DriverManagerl class

DriverManager Jdbc program for loading driving, and creates a link to the database, the API common method as follows:

  • DriverManager.registerDriver(new Driver()):向 DriverManager 注册给定驱动程序
  • DriverManager.getConnection(url, user, password):试图建立到给定数据库 URL 的连接

But in the actual development, the method is not recommended registerDriver registration drive. There are two reasons:

  • View Driver source code can be seen, if used in this way, will cause the driver to be registered twice, have two objects in memory Driver
  • The program relies api mysql, mysql out of the jar package, the program will not compile the program in the future will be very troublesome to switch the underlying database

: Recommended manner Class.forName("com.mysql.jdbc.Driver")
later used in this way does not lead to repeated driven in memory, and used this way, only need a program string does not depend on the specific drivers provide flexibility

Detailed URL database

URL for location identification database, the program tells JDBC URL address through which the database connection, the wording URL is:
Here Insert Picture Description
as follows: protocol + + sub-protocol host: port + database + parameters
wording commonly used database URL address:

  • Oracle写法:jdbc:oracle:thin:@localhost:1521:sid
  • SqlServer写法:jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sid
  • MySql wording: jdbc: mysql: // localhost: 3306 / sid

Note: If the connection is local Mysql database, and the connection port is 3306 then the url address can be abbreviated as: jdbc: mysql: /// database

Connection类

Jdbc program Connection, which is used to link the database on behalf of, Collection database programming is the most important subject, all interactions with the database client connection objects are accomplished by commonly used methods of this object:

  • createStatement():创建向数据库发送sql的statement对象
  • prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象
  • execute(String sql):用于向数据库发送任意sql语句
  • addBatch(String sql) :把多条sql语句放到一个批处理中
  • executeBatch():向数据库发送一批sql语句执行

Connection类

Jdbc program for executing ResultSet results represent Sql statement. When the execution result Resultset package, similar to the way a table is employed. ResultSet object maintains a pointer to the cursor line data table, the initial time, the cursor before the first row, the ResultSet.next call () method, so that the cursor can be directed to a particular data line, the data obtaining method call line
ResultSet Since for packaging execution result, it is the object to provide a method for acquiring data get:

  • Obtain any type of data
    - getObject(int index)
    -getObject(string columnName)
  • Gets the specified types of data
    - getString(int index)
    -getString(String columnName)

ResultSet also provides a method for the result set rolling:

  • next():移动到下一行
  • Previous():移动到前一行
  • absolute(int row):移动到指定行
  • beforeFirst():移动resultSet的最前面
  • afterLast() :移动到resultSet的最后面

Release resources

Jdbc program has run, remember to release the program in operation, those objects that interact with the database to create these objects are usually ResultSet, Statement, and Connection objects, especially Connection object, it is very scarce resources, run out must immediately after the release, if not timely Connection, right close, can easily lead to system downtime.

  • Use doctrine Connection is created as late as possible, as much as possible early release
  • To ensure that the resources released code that can run the code also release resources must be placed finally statement

Statement object Introduction

  • Jdbc statement object is used to send SQL statements to the database, would like to complete the database additions and deletions to change search, simply by sending the object CRUD statements to the database
  • Statement object executeUpdate method for transmitting the database to add, delete, change the sql statement, executeUpdate executed, returns an integer (i.e., additions and deletions result in a database statement data lines change)
  • Statement.executeQuery method for sending a query to the database, executeQuery method returns a ResultSet object that represents the query results

CRUD operations

  • create operation
Statement st = conn.createStatement(); 
String sql = "insert into user(….) values(…..) "; 
int num = st.executeUpdate(sql); 
if(num>0){
 System.out.println("插入成功!!!");
}
  • read operation
Statement st = conn.createStatement(); 
String sql = “select * from user where id=1; 
ResultSet rs = st.executeQuery(sql); 
while(rs.next()){ 
//根据获取列的数据类型,分别调用rs的相应方法映射到java对象中 
}
  • update operation
Statement st = conn.createStatement(); 
String sql = “update user set name= ' ' where name= ' ' ";
int num = st.executeUpdate(sql); 
if(num>0){ 
System.out.println(“修改成功!!!"); 
}
  • delete operation
Statement st = conn.createStatement(); 
String sql = “delete from user where id=1;
int num = st.executeUpdate(sql); 
if(num>0){ 
System.out.println(“删除成功!!!"); 
}

Establish JDBC Tools

Because JDBC relevant code are fixed code part, in order to simplify the process, can create a JDBC tools, use can be called directly. JDBC step of establishing tools as follows:
1. Create db.properties file in the package, using the stored database information file, the file as follows:

driver = com.mysql.jdbc.Driver
username = root
password = 123456
url = jdbc:mysql://localhost:3306/jdbcstudy?useSSL=true

2. Util Package Builder, establishing tools JDBCUtils in the packet, as follows:

package com.kuang.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//编写一个工具类简化开发 , 创建连接数据库都是死代码 , 每次写及其不方便 , 还有关闭连接;
public class JDBCUtils {

    private static String driver=null;
    private static String username=null;
    private static String password=null;
    private static String url=null;

    static{
        try {
            //加载配置文件
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(is);
            //读取配置文件
            driver  = properties.getProperty("driver");
            username  = properties.getProperty("username");
            password  = properties.getProperty("password");
            url  = properties.getProperty("url");

            //加载数据库驱动
            Class.forName(driver);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }


    //获取数据库连接对象
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }

    //释放资源
    public static void closeAll(ResultSet resultSet, Statement statement,Connection connection){
        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();
            }
        }

    }
}

3. Use JDBCUtils tools, test JDBC CRUD operations, as follows:

import com.kuang.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//测试JDBC的CRUD
public class Demo01 {

    @Test
    public void insert() {


        Connection connection = null;
        Statement statement = null;

        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.编写Sql语句
            String sql = "INSERT INTO users(id,NAME,PASSWORD,email,birthday) VALUES(5,'wangwu','123456','[email protected]','1979-12-04');";
            //4.执行sql语句
            int i = statement.executeUpdate(sql); //返回受影响的行数

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            JDBCUtils.closeAll(null,statement,connection);
        }

    }

    @Test
    public void delete() {

        Connection connection = null;
        Statement statement = null;

        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.编写Sql语句
            String sql = "delete from users where id = 5";
            //4.执行sql语句
            int i = statement.executeUpdate(sql); //返回受影响的行数

            if (i>0){
                System.out.println("删除成功");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            JDBCUtils.closeAll(null,statement,connection);
        }

    }

    @Test
    public void update() {

        Connection connection = null;
        Statement statement = null;

        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();
            //3.编写Sql语句
            String sql = "update users set name = 'qinjiang' where id = 4";
            //4.执行sql语句
            int i = statement.executeUpdate(sql); //返回受影响的行数

            if (i>0){
                System.out.println("修改成功");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            JDBCUtils.closeAll(null,statement,connection);
        }


    }

    @Test
    public void query() {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.获取数据库连接
            connection = JDBCUtils.getConnection();
            //2.创建statement对象
            statement = connection.createStatement();

            //3.编写Sql语句
            String sql = "select * from users";
            //4.执行sql语句
            resultSet = statement.executeQuery(sql);

            while (resultSet.next()){
                System.out.println(resultSet.getInt("id"));
                System.out.println(resultSet.getString("name"));
                System.out.println(resultSet.getString("password"));
                System.out.println(resultSet.getString("email"));
                System.out.println(resultSet.getDate("birthday"));
            }



        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            JDBCUtils.closeAll(resultSet,statement,connection);
        }

    }



}

Guess you like

Origin blog.csdn.net/qq_41151659/article/details/94841010