0. Overview
This article uses postgreSQL to connect through JDBC data base Examples of common database operations and JDBC API, JDBC's general workflow and JDBC transactions are introduced.
1. Preparations
A. Download and install the postgreSQL database.
B. Build a new one Java Project and import the JDBC driver jar package of postgreSQL.
2. Java connection postgreSQL code example.
- package vertxTest;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.Statement;
- public class PostgreSQLJDBC {
- public static void main(String args[]) {
- Connection c = null;
- Statement stmt = null;
- try {
- Class.forName("org.postgresql.Driver");
- c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/pgsqltest", "postgres", "2016");
- c.setAutoCommit(false); //Automatically submit
- System.out.println("Opened database successfully");
- stmt = c.createStatement();
- String sql = "CREATE TABLE STUDENTS " +
- "(ID TEXT PRIMARY KEY NOT NULL ," +
- " NAME TEXT NOT NULL, " +
- " SEX TEXT NOT NULL, " +
- " AGE TEXT NOT NULL)";
- stmt.executeUpdate(sql);
- System.out.println("Table created successfully");
- stmt.close();
- c.commit();
- c.close();
- } catch (Exception e) {
- System.err.println(e.getClass().getName() + ": " + e.getMessage());
- System.exit(0);
- }
- }
- }
3. Common addition, deletion and alteration checking operations.
A. Classes defining records (optional)
- package vertxTest;
- public class Student {
- private String Id;
- private String Name;
- private String Sex;
- private String Age;
- Student(String Id,String Name, String Sex, String Age) {
- this.Id = Id; //default
- this.Name = Name;
- this.Sex = Sex;
- this.Age = Age;
- }
- public String getId() {
- return Id;
- }
- public void setId(String Id) {
- this.Id = Id;
- }
- public String getName() {
- return Name;
- }
- public void setName(String Name) {
- this.Name = Name;
- }
- public String getSex() {
- return Sex;
- }
- public void setSex(String Sex) {
- this.Sex = Sex;
- }
- public String getAge() {
- return Age;
- }
- public void setage(String Age) {
- this.Age = Age;
- }
- }
B, JDBC table data operation method
- package vertxTest;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class JDBCOperation {
- /**
- * @method getConn() Get the connection to the database
- * @return Connection
- */
- public Connection getConn() {
- String driver = "org.postgresql.Driver";
- String url = "jdbc:postgresql://localhost:5432/pgsqltest";
- String username = "postgres";
- String password = "2016";
- Connection conn = null;
- try {
- Class.forName(driver); //classLoader, load corresponding driver
- conn = (Connection) DriverManager.getConnection(url, username, password);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return conn;
- }
- /**
- * @method insert(Student student) Insert data into tables
- * @return int Number of successfully inserted data bars
- */
- public int insert(Student student) {
- Connection conn = getConn();
- int i = 0;
- String sql = "insert into students (id,Name,Sex,Age) values(?,?,?,?)";
- PreparedStatement pstmt;
- try {
- pstmt = (PreparedStatement) conn.prepareStatement(sql);
- pstmt.setString(1, student.getId());
- pstmt.setString(2, student.getName());
- pstmt.setString(3, student.getSex());
- pstmt.setString(4, student.getAge());
- i = pstmt.executeUpdate();
- pstmt.close();
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return i;
- }
- /**
- * @method delete(Student student) Delete data from tables
- * @return int Successfully delete the number of data bars in the table
- */
- public int delete(String name) {
- Connection conn = getConn();
- int i = 0;
- String sql = "delete from students where Name='" + name + "'";
- PreparedStatement pstmt;
- try {
- pstmt = (PreparedStatement) conn.prepareStatement(sql);
- i = pstmt.executeUpdate();
- System.out.println("resutl: " + i);
- pstmt.close();
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return i;
- }
- /**
- * @method update(Student student) Change the data in the table
- * @return int Successfully changing the number of data bars in the table
- */
- public int update(Student student) {
- Connection conn = getConn();
- int i = 0;
- String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
- PreparedStatement pstmt;
- try {
- pstmt = (PreparedStatement) conn.prepareStatement(sql);
- i = pstmt.executeUpdate();
- System.out.println("resutl: " + i);
- pstmt.close();
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return i;
- }
- /**
- * @method Integer getAll() Query and print the data in the table
- * @return Integer Query and print the data in the table
- */
- public Integer getAll() {
- Connection conn = getConn();
- String sql = "select * from students";
- PreparedStatement pstmt;
- try {
- pstmt = (PreparedStatement)conn.prepareStatement(sql);
- ResultSet rs = pstmt.executeQuery();
- int col = rs.getMetaData().getColumnCount();
- System.out.println("============================");
- while (rs.next()) {
- for (int i = 1; i <= col; i++) {
- System.out.print(rs.getString(i) + "\t");
- if ((i == 2) && (rs.getString(i).length() < 8)) {
- System.out.print("\t");
- }
- }
- System.out.println("");
- }
- System.out.println("============================");
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
C,test class
- package vertxTest;
- public class JDBCTest {
- public static void main(String args[]) {
- JDBCOperation op = new JDBCOperation();
- op.getAll();
- op.insert(new Student("001","Achilles", "Male", "14"));
- op.insert(new Student("002","Bean", "Fmale", "15"));
- op.getAll();
- op.update(new Student("002","Bean", "", "7"));
- op.delete("Achilles");
- op.getAll();
- }
- }
C. Output results
============================ ============================ ============================ 001 Achilles Male 14 002 Bean Fmale 15 ============================ resutl: 1 resutl: 1 ============================ 002 Bean Fmale 7 ============================ |
4. Code Analysis
In the process of adding, deleting and modifying the database mentioned above, we can find its common part, that is, the general process:
(1) Create Connection object and SQL query command string;
(2) Pass in the SQL query command to the Connection object and get the PreparedStatement object.
(3) ExcuteUpdate () or executeQurey() is executed on the PreparedStatement object to get the result.
(4) Close the PreparedStatement object and Connection object successively.
As you can see, when using JDBC, the two most frequently interacted classes are Connection, PreparedStatement, and ResultSet in select.
5. JDBC API
API |
Explain |
java.sql.Connection |
Connection to a specific database (session). The information provided by the database, the supported SQL grammar, stored procedures and the functions of this connection can be obtained through the getMetaData method. Represents the database. - |
java.sql.Driver |
Each driver class must implement the interface, at the same time, each database driver should provide a class to implement the Driver interface. - |
java.sql.DriverManager (Class) |
Manage a set of basic services for JDBC drivers. As part of the initialization, this interface attempts to load the driver referenced in the "jdbc.drivers" system property. It's just an auxiliary class. It's a tool. - |
java.sql.Statement |
Objects used to execute static SQL statements and return their generated results. - |
java.sql.PreparedStatement |
The Statement interface is inherited to represent the object of the precompiled SQL statement, which is precompiled and stored in the PreparedStatement object. This object can then be used to execute the statement multiple times efficiently. - |
java.sql.CallableStatement |
Used to access stored procedures in the database. It provides some ways to specify the input/output parameters used by the statement. - |
java.sql.PreparedStatement |
The Statement interface is inherited to represent the object of the precompiled SQL statement, which is precompiled and stored in the PreparedStatement object. This object can then be used to execute the statement multiple times efficiently. - |
java.sql.CallableStatement |
Used to access stored procedures in the database. It provides some ways to specify the input/output parameters used by the statement. - |
6. General workflow of JDBC
(1) Load Driver
Class.forName("org.postgresql.Driver"); The JAVA specification specifies that all drivers must register drivers in the static initialization code block into the driver manager.
(2) Connecting
conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/pgsqltest","postgres", "2016");
Connection connection is obtained by the static method getConnection(....) of DriverManager, which essentially passes parameters to the connect() method in the actual Driver to get the database connection.
The format of postgreSQL URL:
jdbc:postgresql:(protocol)@XXX.XXX.X.XXX:X X XXXX (IP address and port number): XXXXX (library name used)
MySQL Writing of URL s: jdbc:mysql://192.168.8.21:3306/test
(3) Obtain the Statement object
Statement stmt = conn.createStatement();
(4) Executing sql statements
stmt.executeQuery(String sql); // Returns a query result set.
stmt.executeUpdate(String sql); the // return value is int, indicating the number of entries affecting the record.
sql statements are sent to the database through the connection for execution in order to achieve the operation of the database.
(5) Processing result sets
Using the Connection object to get a Statement, the executeQuery(Stringsql) method in the Statement can use the select statement to query and return a result set. ResultSet, by traversing the result set, you can get the search result of the select statement. The next() method of ResultSet will operate a cursor to read from the front of the first record until the last record.
The executeUpdate(String sql) method is used to execute DDL and DML statements, such as update and delete operations.
Only when the select statement is executed can the result set be returned.
Statement str=con.createStatement(); // Create Statement
String sql="insert into test(id,name)values(1,"+"'"+"test"+"'"+")";
str. executeUpdate(sql);//Execute Sql statement
String sql="select * from test";
ResultSets rs = str. executeQuery (String sql); // Execute Sql statement with result set after execute select statement
// Traversal processing result set information
while(rs.next()){
System.out.println(rs.getInt("id"));
System.out.println(rs.getString("name"))
}
(6) Close database connection
rs.close();
stmt.close();
con.close();
ResultSet Statement Connection is dependent in turn.
Note: Close the resource in the order of ResultSet result set, Statement, and Connection. Because Statement and ResultSet are available only when they need to be connected, it is possible that other Statements need to be connected after the end of use, so Connection cannot be closed now.
7. JDBC transactions
Four characteristics of transactions
(1) Atomicity
The atomicity of transaction refers to that the program contained in the transaction acts as the logical unit of work of the database, and the data modification operations it does are either all or none of them.
Atomic operations, which are inseparable operations, must succeed together and fail together.
(2) Consistency
Transaction consistency means that the database must be in a consistent state before and after a transaction is executed. This feature is called transaction consistency. If the state of the database satisfies all integrity constraints, it is said that the database is consistent.
(3) Separation
Separation means that concurrent transactions are isolated from each other. That is to say, the operation inside a transaction and the data being operated must be blocked and not seen by other transactions that attempt to modify it.
(4) Persistence
Persistence means ensuring that updates to committed transactions are not lost when a system or medium fails. That is, once a transaction is committed, DBMS ensures that its changes to the data in the database should be permanent and can withstand any system failures. Persistence is guaranteed by database backup and recovery.