JDBC technology [JDBC overview, obtain database connection, download database driver] (1) - comprehensive detailed explanation (learning summary --- from entry to deepening)

 

Table of contents

Overview of JDBC

JDBC writing steps 

 get connection

 Download the database driver

Get database connection

 Use of Properties files


Overview of JDBC

data persistence

Persistence: Save the data in memory to a storage device (such as a disk) that can be stored permanently.

The main application of persistence is to store data in memory in a relational database, and of course it can also be stored in disk files and XML data files.

 

 What is JDBC

1. JDBC (Java DataBase Connectivity) java database connection

2. It is a technical specification under the JavaEE platform

3. Define the standard API for connecting to the database and executing SQL statements in the Java language

4. It can provide unified access for various relational databases

What is a database driver 

1. The database driver is a program that directly operates the database

2. The database driver names of different data products are different

3. In the program, you need to rely on the database driver to complete the operation on the database

Accessing Database Technology in Java

 1. Access database based on JDBC standard

 2. Use a third-party ORM framework, such as Hibernate, Mybatis, etc. to access the database

Program operation database process

If there is no JDBC, then the Java program accesses the database like this:

 With JDBC, the Java program accesses the database like this:

 Classes and interfaces commonly used in JBDC

Driver interface

The role of the Driver interface is to define some capabilities that the database driver object should have. For example, the definition of the method of establishing a connection with the database. This interface is provided to database manufacturers. All databases that support Java language connections have implemented this interface. The class that implements this interface is called a database driver class.

 DriverManager class

DriverManager is a driver manager and is responsible for managing database drivers. After the driver is registered, it will be saved in the registered list in DriverManager. DriverManager can establish a connection between the application program and the database through the instantiated database driver object. And return the database connection object of Connection interface type.

getConnection(String jdbcUrl, String user, String password) This method returns the Connection object of the corresponding database through the url, user and password of the access database. JDBC URL is used to connect to the specified database identifier when connecting to the database. The URL includes information such as the type, address, port, and library name of the database. The connection URLs for databases of different brands are different.

Connect to MySql database:

Connection conn = DriverManager.getConnection
("jdbc:mysql://host:port/database", "user","password");

Connect to the Oracle database:

Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@host:port:database","user", "password");

Connection interface

Connection is the connection (session) object of the database. All operations on the database are performed on the basis of this connection, and we can execute sql statements through this object and return the results.

common method

1. createStatement() creates an object of the Statement interface type that sends sql to the database.

2. preparedStatement(sql) creates an object of PrepareSatement interface type that sends precompiled sql to the database.

3. setAutoCommit(boolean autoCommit) Set whether the transaction is automatically committed.

4. commit() commits the transaction on the link.

5. rollback() rolls back the transaction on this link.

 Statement interface

An object used to execute a static SQL statement and return the results it generates. Created by createStatement to send simple SQL statements (dynamic binding is not supported).

common method

1. execute(String sql) executes the SQL in the parameter, and returns whether there is a result set.

2. executeQuery(String sql) runs the select statement and returns the ResultSet result set.

3. executeUpdate(String sql) runs insert/update/delete operations and returns the number of updated rows.

4. addBatch(String sql) Put multiple sql statements into a batch.

5. executeBatch() sends a batch of sql statements to the database for execution.

PreparedStatement interface

Inherited from the Statement interface and created by preparedStatement, it is used to send SQL statements containing one or more parameters. The PreparedStatement object is more efficient than the Statement object. Because it implements dynamic parameter binding, it can prevent SQL injection, so we generally use PreparedStatement. 

 common method

1、addBatch()

Add the current sql statement to a batch.

2、execute()

Execute the current SQL and return a boolean value

3、executeUpdate()

Runs insert/update/delete operations and returns the number of updated rows.

4、executeQuery()

Execute the current query and return a result set object

5、setDate(int parameterIndex, Date x)

Bind a java.sql.Date value to the specified position in the current SQL statement

6、setDouble(int parameterIndex, double x)

Bind a double value to the specified position in the current SQL statement

7、setFloat(int parameterIndex, float x)

Bind a float value to the specified position in the current SQL statement

8、setInt(int parameterIndex, int x)

Bind an int value to the specified position in the current SQL statement

9、setString(int parameterIndex, String x)

Bind a String value to the specified position in the current SQL statement

 ResultSet interface

ResultSet is used to temporarily store the result set obtained by database query operation.

common method

1、getString(int index)、getString(String columnName)

Obtain data objects of types such as varchar and char in the database.

2、getFloat(int index)、getFloat(String columnName)

Get the data object of type Float in the database.

3、getDate(int index)、getDate(String columnName)

Get the date type data in the database.

4、getBoolean(int index)、getBoolean(String columnName)

Get the data of Boolean type in the database.

5、getObject(int index)、getObject(String columnName)

Get data of any type in the database.

JDBC writing steps 

 Note: ODBC (Open Database Connectivity, Open Database Connectivity) is launched by Microsoft under the Windows platform. The user only needs to call the ODBC API in the program, and the ODBC driver will convert the call into a call request to a specific database.

 get connection

 Download the database driver

MySQL :: Download MySQL Connector/J (Archived Versions)

Get database connection

/**
* 获取数据库连接测试类
*/
public class JdbcTest {
     public static void main(String[] args) throws ClassNotFoundException, SQLException
      {
        //连接Mysql数据库的URL
        String url = "jdbc:mysql://localhost:3306/itjdbc";
        //连接数据库的用户名
        String name = "root";
        //连接数据库的密码  
        String pwd01 = "";
        //通过反射实现数据库驱动的加载与注册
        Class.forName("com.mysql.jdbc.Driver");
        //通过DriverManager对象获取数据库的连接对象
        Connection connection = DriverManager.getConnection(url, name, pwd);
        System.out.println(connection);
     }
}

When the com.mysql.jdbc.Driver class information is loaded, the code in the static block is executed. In the static block, the database driver will instantiate itself and register itself in the DriverManager driver manager through the registerDriver method of DriverManager.

 Use of Properties files

 properties file introduction

The file with the suffix properties is a property file. This file stores content in key=value format. You can use the Properties tool class in Java to read this file. Some configuration information will be put into the properties file in the project, so the properties file is often used as a configuration file.

 Properties tool class

The Properties tool class is located in the java.util package, and the tool class inherits from Hashtable. The configuration file of type .properties can be read through the Properties tool class.

 Common methods in the Properties tool class

load(InputStream is) reads the properties file and parses it through the given input stream object

getProperty(String key) Get the corresponding value according to the key

Note: If the properties file contains Chinese, then the idea needs to be set.

 

 properties file

#我是中国人
key1=ITBZ
key2=BJSXT
key3=我是中国人

Manipulating the properties file

/**
* 读取properties配置文件的测试类
*/
public class PropertiesTest {
    public static void main(String[] args) throws IOException {
        //实例化Properties对象
        Properties prop = new Properties();
        //获取读取properties文件的输入流对象
        InputStream is = PropertiesTest.class.getClassLoader().getResourceAsStream("test.properties");
       //通过给定的输入流对象读取properties文件并解析。
        prop.load(is);
        //获取properties文件中的内容
        String value1 =prop.getProperty("key1");
        String value2 =prop.getProperty("key2");
        String value3 =prop.getProperty("key3");
        System.out.println(value1+""+value2+" "+value3);
   }
}

Optimizing access to database connections

Storing the information needed to connect to the database in the properties file can solve the problem of hard coding.

 properties file content

#连接Mysql数据库的URL
url=jdbc:mysql://localhost:3306/itjdbc
#连接数据库的用户名
username=root
#连接数据库的密码
pwd= XXXX
#数据库驱动名称
driver=com.mysql.jdbc.Driver

get connection

/**
* 优化获取数据库连接
*/
public class JdbcTest2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException,
SQLException {
        //实例化Properties对象
        Properties prop = new Properties();
        //获取读取properties文件的字节输入流对象
        InputStream is = JdbcTest2.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //读取properties文件并解析
        prop.load(is);
        //获取连接数据库的url
        String url = prop.getProperty("url");
        //获取连接数据库的用户名
        String name = prop.getProperty("username");
        //获取连接数据库的密码
        String pwd = prop.getProperty("pwd");
        //获取数据库驱动全名
        String drivername = prop.getProperty("driver");
        //加载并注册驱动
        Class.forName(drivername);
        //通过驱动管理器对象获取连接对象
        Connection connection = DriverManager.getConnection(url, name, pwd);
        System.out.println(connection);
   }
}

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131648625