JDBC database connection technology

######JDBC


-Java DataBase Connectivity, java database connection, in fact jdbc is a set of api (application program interface) in java that interacts with the database

 

##### Why use JDBC


-Because java needs to connect to multiple databases, in order to avoid each database learning a new set of APIs, Sun has defined a set of jdbc standards (interfaces, method declarations), and various database vendors write method implementations based on this interface ( Database driver), so java programmers only need to master the method invocation of the jdbc interface, master a set of methods to connect to any database, and a set of code that follows the jdbc standard can connect to any database

    Extranet: maven.aliyun.com
pom.xml introduces jar package address <dependencies> </ dependencies>
##### How to use jdbc
1. Create maven project
2. Maven extranet search mysql jar package and put it in the project The
operation of pom.xml is as follows:
                // 1. Register driver
// com.mysql.jdbc.Driver
        Class.forName ("com.mysql.jdbc.Driver");
        // 2. Get connection object
        Connection connection = DriverManager.getConnection ("jdbc: mysql: // localhost: 3306 / db3", "root", "lf215000");
        System.out.println (connection);
        // 3. Create SQL execution object
        Statement statement = connection.createStatement ();
        // 4. Execute SQL
// String sql = "create table if not exists jdbct1 (id int, name varchar (10))"; // Create if it does not exist
        String sql="drop table if exists jdbct1";
        statement.execute(sql);
        System.out.println("执行成功!");
        //5.关闭资源
        statement.close();
        connection.close();

##### Method of executing SQL objects


-execute (sql) The return value of this method represents whether there is a result set (boolean), this method can execute any SQL, but it is recommended to execute DDL (data definition language create drop alter truncate)
-executeUpdate (sql) can perform the addition, deletion and modification of this method The return value is of type int indicating the number of rows in effect
-executeQuery (sql) executes the query SQL statement and the return value is the result set

 

###### Comparison of database type and java type


   mysql                        java
   int                              getint
   varchar                     getString
   float/double               getfloat/getDouble
   datetime/timestamp  getDate


   
###### resultSet Two ways to get data


1.getString (field name)
2.getString (position of query result field) starts from 1

###### Properties property configuration object
-used to read the data in the * .properties configuration file (key-value pair key: value)
-usage:
            // Create a property object
            Properties properties = new Properties ();
            / / Get the file input stream
            InputStream inputStream = Demo04.class.getClassLoader (). GetResourceAsStream ("jdbc.properties");
            // Load the file into the properties with the object
            properties.load (inputStream);
            // Read the data
            String name = properties.getProperty ("name");
            // Anything read is of type
            String age = properties.getProperty ("age");
            System.out.println ("name =" + name + "age =" + age);


#### DBCP database connection pool
-DataBase Connection Pool
-Why use database connection pool:

If there is no database connection pool, the web server needs to establish a connection every time it interacts with the data. After using it, close the connection. If there are 10,000 interactions, there will be 10,000 connection opening and closing. Frequent switching on and off connections is a waste of resources. Using the database connection pool, you can set the initial number of connections and the maximum number of connections. Each interaction with data will be disconnected from the connection pool and then put back into the connection pool instead of disconnecting to condense, so that you can play the connection The role of database reuse to avoid waste of resources
-how to use the database connection pool


######Statement和PreparedStatement


-PrepareStatement pre-compiled SQL execution object
1. The advantage is that SQL injection can be avoided because the logic of the SQL has been specified at compile time, and the logic will not be changed because of the content that is replaced
. 2. If the SQL involves variables compared to the statement string stitching method , The code readability is improved, and it is not easy to make mistakes
. 3. If the use of PreparedStatement is more efficient if it involves batch execution of multiple SQLs 
-if there is no variable in SQL, use Statement and variable use PreparedStatement
   

####### Batch operations

-Statement batch
            statement = connection.prepareStatement (sql);
            for (int i = 0; i <100; i ++) {
                statement.setString (1, "name" + i);
                statement.setString (2, "admin" + i );
                // Add batch operation
                statement.addBatch ();
                if (i% 20 == 0) {
                    // Execute batch operation
                    statement.executeBatch ();
                    // Empty the executed SQL
                    statement.clearBatch ();
                }
            }
            / / Perform batch operations and close the residual
            statement.executeBatch ();


####### Transactions


1. Turn on and off automatic submission
    connection.setAutoCommit (false / true);
2. Submit transaction
    connection.commit ();
3. Roll back
    connection.rollback ();

-Realize transfer:
 Superman 500 Batman 5000
 Batman transfer to Superman 2000
The first successful
execution The second successful
execution The third failure Failed that the balance is insufficient and rolled back

create table jdbc_person (id int,name varchar(10),money int);
insert into jdbc_person values(1,'超人',500),(2,'蝙蝠侠',5000);

-Code reference demo08.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Demo08 {
    public static void main (String [] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtils.getConnection ();
            statement = connection.createStatement (); 
            // Open transaction (turn off automatic submission)
            connection.setAutoCommit (false);
            // Prepare to transfer SQL
            String sql1 = "update jdbc_person set money = money-2000 where id = 2";
            String sql2 = "update jdbc_person set money = money + 2000 where id = 1 ";
            // Execute transfer
            statement.executeUpdate (sql1);
            statement.executeUpdate (sql2);
            // Query whether Batman's remaining money is greater than or equal to 0
            String sql3 = "select money from jdbc_person where id = 2";
            resultSet = statement.executeQuery (sql3);
            while (resultSet.next ()) {
                int money = resultSet.getInt ("money");
                if (money> = 0) {// money is enough
                    connection.commit ();
                    System.out.println ("Transfer successful");
                } else {// money is not enough
                    connection.rollback ();
                    System.out.println ("Transfer failed");
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            DBUtils.close(connection, statement, resultSet);
        }
    }
}
 

 

###### Get the value of the increment primary key


   create table team (id int primary key auto_increment,name varchar(10));
   create table player(id int primary key auto_increment,name varchar(10),tid int);
null

Example:

Yao Ming Rockets

Team table
id name
 1 Rockets
Player table
id name tid
   Yao Ming 1

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class Demo09 {

    public static void main (String [] args) {
        Scanner sc = new Scanner (System.in);
        System.out.println ("Please enter the team name:");
        String teamName = sc.nextLine ();
        System.out .println ("Please enter player name:");
        String playerName = sc.nextLine ();
        sc.close ();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtils.getConnection ( );
            // First check if the team exists. If there is a team id
            String s = "select id from team where name =?";
            Statement = connection.prepareStatement (s);
            statement.setString (1, teamName);
            resultSet = statement.executeQuery ();
            int teamId = -1;
            while (resultSet.next ()) {
                // Query the report from the database
                teamid teamId = resultSet.getInt ("id");
            }
            if (teamId ==- 1) {// The team has not been saved before
                String sql = "insert into team values ​​(null ,?)";
                // Creating a statement multiple times will warn that it is not closed, and close the previous statement
                statement.close () before warning ;
                statement = connection.prepareStatement (sql, Statement.RETURN_GENERATED_KEYS);
                statement.setString (1, teamName);
                statement.executeUpdate ();    
                // Get auto-increment primary key
                resultSet.close ();
                resultSet = statement.getGeneratedKeys();
                while(resultSet.next()) {
                    teamId=resultSet.getInt(1);
                }
            }
            //之前保存过球队
            //插入球员
            String sql1 =  "insert into player values(null,?,?)";
            statement = connection.prepareStatement(sql1);
            statement.setString(1, playerName);
            statement.setInt(2, teamId);
            statement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection, statement, resultSet);
        }
    }

}
 


##### Source Data
-Source data refers to database and table related information

Example:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

/ **
 * Source data (database basic information or table basic information)
 * @author BARCA 球王 = Andrew Feng
 * @version 1.0
 * @see      
 * @since
 * /
public class Demo10 {
    public static void main (String [] args) {
         Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtils.getConnection ();
            statement = connection.createStatement ();
            // Get database source data object
            DatabaseMetaData metaData = connection.getMetaData ();
            System.out.println ("Drive Version" + metaData.getDriverVersion ());
            System.out.println ("user name" + metaData.getUserName ());
            System.out.println ("connection address" + metaData.getURL ());
            System.out.println ("database name" + metaData.getDatabaseProductName ());
            
            // Get the metadata of the table
            resultSet = statement.executeQuery ("select * from emp");
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData ();
            // Get the field of the table
            int columCount = resultSetMetaData.getColumnCount ();
            
            / / Get the field name
            for (int i = 0; i <columCount; i ++) {
                String name = resultSetMetaData.getColumnName (i + 1);
                String type = resultSetMetaData.getColumnTypeName (i + 1);
                System.out.println(name+":"+type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.close(connection, statement, resultSet);
        }
    }
}


 

Posted 33 original articles · praised 4 · visits 2717

Guess you like

Origin blog.csdn.net/qq_41650000/article/details/83317379