Introduction to JDBC
JDBC is all called: Java Data Base Connectivity (Java database connection), which is mainly composed of interfaces.
2 packages that make up JDBC:
java.sql
Javax.sql
The development of JDBC applications requires the support of the above 2 packages, as well as the implementation of the corresponding JDBC database (that is, database driven).
In order to simplify and unify the operation of database, Sun Company defines a set of Java Operation Database specification, called JDBC.
First, the development of JDBC to write steps
Encoding Step
A, registered driver DriverManager
Drivermanager.registerdriver (New Com.mysql.jdbc.Driver ());
Class.forName ("Com.mysql.jdbc.Driver");
b, establish the connection Connection
Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day12", "root", "sorry");
C, create an object to send SQL and send SQL Statement
Statement stmt = Conn.createstatement ()
D, Get results ResultSet
ResultSet rs = stmt.executequery (SQL);
E, closing resource close ()
The sample code is as follows:
1, registration driver DriverManager
drivermanager.registerdriver (New Com.mysql.jdbc.Driver ());
2, establish the connection with the database Connection
Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day12", " Root "," sorry ");
SYSTEM.OUT.PRINTLN (conn);
3, get the SQL statement sent Statement
Statement stmt = Conn.createstatement ();
String sql = "Select Id,name,password,email,birthday from users";
ResultSet rs = stmt.executequery (sql);
4. ResultSet while
(Rs.next ()) {
System.out.println (rs.getobject ("id")) encapsulated the result;
System.out.println (Rs.getobject ("name"));
System.out.println (Rs.getobject ("password"));
System.out.println (Rs.getobject ("email"));
System.out.println (Rs.getobject ("Birthday"));
System.out.println ("--------------------------------------");
}
5, Release Resources
Rs.close ();
Stmt.close ();
Conn.close ();
DriverManager Detailed
The DriverManager in the JDBC program is used to load drivers and create links to the database, a common method of this API:
Drivermanager.registerdriver (New Driver ());
Drivermanager.getconnection (URL, user, password);
Note: It is not recommended to use the Registerdriver method to register the driver in actual development.
There are two reasons:
See driver source code can be seen, if this way, will cause driver registration two times, that is, in memory there will be two driver objects. The program relies on the MySQL API, leaving the MySQL jar package, the program will not compile, the future program to switch the underlying database will be very cumbersome.
Recommended way: Class.forName ("Com.mysql.jdbc.Driver");
The sample code is as follows:
1, registration driver DriverManager
//drivermanager.registerdriver (New Com.mysql.jdbc.Driver ());
Class.forName ("Com.mysql.jdbc.Driver");
2, establish the connection with the database Connection
Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/day12", " Root "," sorry ");
SYSTEM.OUT.PRINTLN (conn);
3, get the SQL statement sent Statement
Statement stmt = Conn.createstatement ();
String sql = "Select Id,name,password,email,birthday from users";
ResultSet rs = stmt.executequery (sql);
4. ResultSet while
(Rs.next ()) {
System.out.println (rs.getobject ("id")) encapsulated the result;
System.out.println (Rs.getobject ("name"));
System.out.println (Rs.getobject ("password"));
System.out.println (Rs.getobject ("email"));
System.out.println (Rs.getobject ("Birthday"));
System.out.println ("--------------------------------------");
}
5, Release Resources
Rs.close ();
Stmt.close ();
Conn.close ();
This approach does not cause the drive object to recur in memory, and in this way, the program only needs a string, does not need to rely on a specific driver, making the program more flexible.
Similarly, it is not recommended to use specific drive types in development to point to the connection object returned by the Getconnection method.
Database URL
URL is used to identify the location of the database, the programmer through the URL address to tell the JDBC program to connect which database, the URL is written as:
Common database URL address to the wording:
Oracle notation: Jdbc:oracle:thin: @localhost: 1521:sid
sqlserver-jdbc:microsoft:sqlserver://localhost:1433; Databasename=sid
Mysql-jdbc:mysql://localhost:3306/sid
Shorthand for MySQL URL address: jdbc:mysql:///sid
Connection detailed
Connection in the JDBC program, which is used to represent the links of the database, collection is the most important object in database programming, and all interactions between client and database are done through connection objects, the common method of this object:
Createstatement (): Creates a statement object that sends SQL to the database. Preparestatement (SQL): Creates a Preparesatement object that sends precompiled SQL to the database. Preparecall (SQL): Creates a CallableStatement object that executes a stored procedure. Setautocommit (Boolean autocommit): Sets whether a transaction is automatically committed. Commit (): commits a transaction on a link. Rollback (): ROLLBACK transaction on this link. statement detailed
The
Statement object in the JDBC program is used to send SQL statements to the database.
Classification of statements in the database:
Ddl:data definition lanaguage. Data definition language. Manipulate the object database, the structure of the table
CREATE DROP ALTER
Dml:data Manager Language. Data manipulation language. The action object is the record in the table
INSERT DELETE UPDATE
dql:data query lanaguage. Data Query Language. The action object is the record in the table
SELECT
Dcl:data control lanaguage. Data Control Language. such as permissions
GRANT
Statement Objects common methods:
ExecuteQuery (String sql): Used to send query statements to data. Executeupdate (String sql): used to send an INSERT, UPDATE, or DELETE statement to the database execute (String sql): used to send arbitrary SQL statements to the database Addbatch (String sql) : Put multiple SQL statements into a batch. ExecuteBatch (): Sends a batch of SQL statement execution to the database. Note: A, executequery (String?sql) is used to send query statements to the data. SQL can only be DQL statements
Returns the result of the ResultSet type.
B, Executeupdate (string?sql): To send an INSERT, UPDATE, or DELETE statement to a database, SQL can only be a DML statement.
Returns the result of the type int. Represents the deletion of additions and deletions, which resulted in changes to several rows of data in the database.
C, execute (String SQL): Use to send arbitrary SQL statements to the database. DDL, DML, DQL, DCL are available
Return is a Boolean result, but it does not represent the success of the statement execution.
ResultSet detailed
The resultset in the JDBC program is used to represent the execution results of the SQL statement. ResultSet encapsulates execution results in a table-like manner. The ResultSet object maintains a cursor that points to the table data row, and at the beginning, the cursor calls the Resultset.next () method before the first row, allowing the cursor to point to a specific data row, making the calling method fetch the data for the row.
ResultSet is used to encapsulate execution results, so this object provides a get method for fetching data:
Get data of any type
GetObject (int index) GetObject (string columnName) Gets the data of the specified type (convenient for encapsulating data), for example:
getString (int index) getString (String columnName) common data type conversion table
ResultSet also provides a way to scroll the result set:
Next (): Move to the next line Previous (): Move to the previous line of absolute (int row): Move to the specified row Beforefirst (): Move the front of the resultset. Afterlast (): Move to the last side of the resultset. Releasing Resources
When the JDBC program finishes running, remember to release the objects that the program has created to interact with the database during its run, usually resultset, statement, and connection objects.
Especially connection objects, it is very rare resources, after use must immediately release, if the connection can not be timely, correct shutdown, very easy to cause system downtime. The principle of connection is to create as late as possible and release as early as possible.
To ensure that the resource release code runs, the resource release code must also be placed in the finally statement.
PreparedStatement
Preperedstatement is a child of statement, and its instance object can be obtained by invoking the Connection.preparedstatement () method relative to the statement object:
Preperedstatement can avoid problems with SQL injection. Statement causes the database to compile SQL frequently, potentially causing a database buffer overflow. PreparedStatement SQL can be precompiled to improve the efficiency of database execution. preperedstatement for parameters in SQL, the substitution of placeholders is allowed, simplifying the writing of SQL statements.
Database Page Paging
MySQL Paging implementation:
Select * FROM table limit M,n
M: Record Start index location
N: How many records to take.
pagination display of Web pages
Get the total number of records that need to be paged, and then display the page number in the Web page.
Depending on the page number, querying the corresponding records from the database appears in the Web page.
Both of these actions are typically encapsulated using the Page object.