JDBCJDBC Introduction
Java is the use of JDBC technology to achieve data access, JDBC is the Java database (Java connectivity) technology abbreviation, it acts as a Java application and a variety of databases between the media, bar data persistence, this is a persistence mechanism
How JDBC Works
JDBC API
An interface provided by Sun that includes various different database interactions for Java applications, such as connection (connection) Statement (Execute SQL command) ResultSet (return result set) PreparedStatement interface.
JDBC Driver Manager
JDBC Driver Manager, responsible for a variety of JDBC drivers, connecting Java applications to the JDBC driver, located under the JDK's java.sql package
JDBC Driver
provided by each manufacturer, responsible for connecting different databases, MySQL and Oracle require different databases.
Introduction to the JDBC API
DriverManager: Load the driver and provide support for creating a database connection
Connection: Responsible for connecting data volumes and transferring data tasks
Statement: Generated by connection, responsible for executing SQL statements
ResultSet: Responsible for saving the result set returned by statement execution
PreparedStatement: Is the statement sub-interface, generated by connection, is also responsible for executing SQL statements. He's more secure, and highly readable.
Steps for JDBC to access a database
- Load the JDBC driver (may throw an exception, so use Classnotfoundexeception to declare Try--catch)
A) class.forname ("JDBC Driver class name");
- Establish a connection to the database
A) Connection conn=drivermanager.getconnection ("Database connection string", "Database user name", "password");
- An SQL statement occurs, and the result is returned
A) Statement st=conn.createstatement (); To create an object that executes an SQL statement
b) ResultSet rs=statement.executequery ("SQL statement"); return result set
- Processing the returned results
while (Rs.next ()) {//determines if there is data for the next row
Read
Int id=rs.getint ("id"); or int id=rs.getint (0);
};
connecting databases using pure Java to connect to a database
Need to introduce a jar package, Mysql-connector-java-5.1.0-bin.jar
Package cn.jbit.example02;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Org.apache.log4j.Logger;
public class Example02 {
private static Logger Logger=logger.getlogger (Example02.class.getName ());
public static void Main (string[] args) {
Connection Conn=null;
Load Driver
try {
Class.forName ("Com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
Todo:handle exception
Logger.error (e);
}
try {
Conn=drivermanager.getconnection ("Jdbc:mysql://localhost:3306/myschool", "root", "root");
Logger.warn ("Established connection succeeded");
SYSTEM.OUT.PRINTLN ("Established connection succeeded");
} catch (Exception e) {
Todo:handle exception
Logger.error (e);
}finally {
try {
if (null!=conn) {
Conn.close ();
SYSTEM.OUT.PRINTLN ("Close connection succeeded!! ");
}
} catch (Exception e) {
Todo:handle exception
Logger.error (e);
}
}
}
}
These are the steps to connect to the database
Statement interface and ResultSet interface
Method of Connection interface
|
Method name |
Role |
|
Void Close () |
Release connection Resources Now |
|
Statement crementstatement () |
Creates an statement object, in which SQL statements are sent to the database |
|
PreparedStatement preparedstatement (String sql) |
Create a PreparedStatement object to send the entrant SQL statement to the database |
|
Boolean Iscloseed () |
Query whether connection is closed |
Common methods of statement interface
|
Method name |
Role |
|
Result ExecuteQuery (String sql) |
Executes the SQL query and returns the ResultSet object |
|
Int executeupdate (String sql) |
You can perform insert,update,delete operations to return the number of affected rows |
|
Boolean execute (String sql) |
Arbitrary SQL statements can be executed, and if the result object is executed, returns true if the update count is performed or the non-existent results return false |
Common methods for ResultSet interfaces
|
Method name |
Role |
|
Boolean Next () |
To judge, move the cursor to the next line in the current position |
|
Boolean Previous () |
Move the cursor to the previous line |
|
Void Close () |
Close the ResultSet object |
|
int getInt (int cloumnindex) |
Gets the value of the column in the form of an int subscript |
|
int getInt (int cloumnname) |
Gets the value of the column as an int column name |
|
float getfloate (int cloumnindex) |
Gets the value of the column as a float subscript |
|
Float getfloat (int cloumnname) |
Gets the value of the column in the form of a float column name |
|
String getString (int cloumnindex) |
Gets the value of the column as a string subscript |
|
String getString (int cloumnname) |
Gets the value of the column as a string column name |
|
Int GetRow () |
Gets the line number of the line that the cursor is currently referring to |
|
Boolean Absolute (int row) |
Moves the cursor to the specified line |
PreparedStatement interface
In order to prevent SQL injection attacks, the statement interface method is to make a concatenation of the SQL statements. Not only trouble but also has a security risk, PreparedStatement solves this problem
Use: PreparedStatement interface
|
Method name |
Role |
|
Boolean Execute () |
' Can execute arbitrary SQL statements, return TRUE if the result object is executed, or False if the update count or nonexistent result is executed |
|
ResultSet ExecuteQuery () |
Executes a SQL query that returns an ResultSet object |
|
Int executeupdate () |
You can perform insert,update,delete operations to return the number of affected rows |
|
Void setint (int index,int x) |
Sets the specified parameter to the Java int value, which is the format of the SQL statement above (? ) Set the value before: Subscript 1 start, after: value |
|
Void setobject (int index,int x) |
Given object settings specify parameters |
Steps:
Create a PreparedStatement object
The PreparedStatement object is created by connection's PreparedStatement (String sql) method, and the SQL statement can have one or more parameters with one value. Placeholder representation.
String sql=update dog set name=?,health=? Where id=?
PreparedStatement ps=conn.preparedstatement (String sql);
Set values for each placeholder's parameter
Ps.setint (int index,int values); First: is the subscript starting from 1, the second: is the value
ps.setstring (int index,stringvalues); First: is the subscript starting from 1, the second: is the value
Execute SQL statement
After setting each parameter value, you can call PreparedStatement's method (ResultSet executeQuery), int execute (), Boolean execute ()
Java uses JDBC