JDBC principle,
What is JDBC:
Java Database Connectivity: Java Database access solutions
JDBC is a milestone solution for Java applications to access databases. Java developers want to access different databases in the same way to implement Java operation interfaces unrelated to specific databases.
JDBC defines a set of standard interfaces, that is, common APIs for accessing databases. Different database vendors implement these interfaces according to their own database features.
JDBC only defines interfaces. Each database vendor is responsible for the specific implementation.
Programmers only need to call interfaces. The actual calling is the implementation part of the underlying database vendor.
Figure-2 process of accessing the database through JDBC
JDBC database access process:
- Load drivers and establish connections
- Create statement object
- Execute SQL statements
- Processing result set
- Close connection
Follow these steps to connect JDBC to a mysql database:
1. Class. forName ("com. mysql. jdbc. Driver"; // load the mysql Driver Class.
2. Create a connection through the DriverManager class. The basic information is as follows:
Connection conn = DriverManager. getConnection ("url", "username", "pwd ");
Url: The address used to connect to the local database.
Jdbc: mysql: // localhost: 3306/emplist Host Name: Port Number/Database Name
Username: the username used to access the mysql database.
Pwd: Password
You can connect to the database.
3. The Statement interface is used to process the SQL Statement objects sent to the database. It is created through the Connection object. There are three common methods:
Statement stems = conn. createSatement ()
// 1.exe cute method. If the executed SQL statement is a query statement and a result set exists, true is returned. If a non-query statement or no result set exists, false is returned.
2. boolean flag = stems.exe cute (SQL );
// 2. excuteuapdate method. If the DML statement is executed, the number of affected records is returned.
Int I = stems.exe cuteUpdate (SQL)
// 3.exe cuteQuery method. If the DQL statement is executed
ResutlSet rs1_stems.exe cuteQuery (SQL );
4. ResultSet Interface
The execution of DQL query statements is received by the ResultSet interface,
Common Processing Methods: traverse/determine whether results exist:
Example: String SQL = "select * from emp ";
ResultSet rs = stems. exceuteQuery (SQL
While (rs. next ()){
System. out. println (rs. getInt ("empno") +"
+ Rs. getString ("ename "));
}
The query results are stored in a series of rows of the ResultSet object. The first position of the pointer is at the beginning of the row. The next () method is used to move the cursor between rows. The getXXX () method is used to obtain the field content.