This chapter documents the simple use of JDBC!
The role of 0,JDBC
1,jdbc Getting Started preparation work
2,JDBC Registered Driver
3, using JDBC for database crud
The role of 0,JDBC
Establishes a connection to the database, sends statements that manipulate the database, and processes the resulting results.
1,jdbc Getting Started preparation work
0), use JDBC to manipulate the jar used by MySQL
Mysql-connector-java-5.1.22-bin.jar
1), create database qogir user name root password root
CREATE TABLE use
2,JDBC Registered Driver
0), register MySQL driver (3 ways)
Register the database driver, we can establish a connection with the database and read and write to the database operation.
Because the driver only needs to register once, we register it in the static code block
The first way: to register the driver with the driver Association class, the disadvantage is that when the database is replaced (for example, MySQL is changed to Oracle), the program will have a compilation problem when the MySQL jar is removed.
static { try { java.sql.DriverManager.registerDriver (new Com.mysql.jdbc.Driver ()); } catch ( SQLException e) { e.printstacktrace (); }}
View the source code for the Registerdriver method: we can see that the driver is actually encapsulated in a driverinfo and then placed in a vector.
The second way: it is recommended to use this method to facilitate flexible configuration of the drive
static{ try { class.forname ("Com.mysql.jdbc.Driver"), } catch (ClassNotFoundException e) { throw new Exceptionininitializererror (e); }}
Using Class.forName to load the driver class, the driver class actually registers the driver when the load is initialized
View Com.mysql.jdbc.Driver Source code: It can be found that it actually used the first way to register the driver
The third Way: Set the description-driven key-value pair to the system properties
static { System.setproperty ("Jdbc.drivers", "Com.mysql.jdbc.Driver");}
You can register multiple drivers in this way, with multiple drivers separated by ":"
For example, loading MySQL and Oracle drivers
System.setproperty ("Jdbc.drivers", "Com.mysql.jdbc.Driver:oracle.jdbc.driver.OralceDriver");
When you use DriverManager to get a database connection, DriverManager is loaded and initialized
Drivermanager.getconnection (Url,username,password);
If the source code sees the third way or registers the driver using the second method, the driver registration is ultimately the first way.
3, using JDBC for database crud
1), registered driver, as described above
2), get the database connection
This URL format: JDBC: Sub-Protocol: Sub-name//hostname: Port/Database name
There is no sub-name, if the database is local and the port number is the default port number, you can omit localhost:3306, write directly as Jdbc:mysql:///qogir
private static string url = "Jdbc:mysql://localhost:3306/qogir";p rivate static string username = "root";p rivate static STR ing password = "root";p ublic static Connection getconnection () throws SQLException { return Drivermanager.getconnection (Url,username,password);}
3), create a tool class object that sends a simple SQL statement to execute without parameters to the database, based on a database connection already established
Statement Statement = Null;statement = Connection.createstatement ();
4), send SQL statements to the database to get the result set
ResultSet ResultSet = Null;resultset = Statement.executequery ("Select Id,name,password from user");
5), processing the result set
while (Resultset.next ()) { System.out.println (resultset.getstring ("id") + "---->" +resultset.getstring ("name ") +"---> "+resultset.getstring (" password ");}
6), releasing the resources, releasing the resources in the order that they should release the result set, release the statement, release the database connection order
Also, in order not to take up too much resources, the database connection should be set up to be released as short as possible.
public static void Close (ResultSet rs,statement st,connection con) {if (rs! = null) {try {rs.close ();} catch (SQLException e) {E.printstacktrace ();}} if (st! = null) {Try{st.close ();} catch (SQLException e) {e.printstacktrace ()}} if (con! = null) {Try{con.close ();} catch (SQLException e) {e.printstacktrace ();}}}
Finally get the result
Understanding the read operation of JDBC, and then understand the JDBC write operation should be very easy, specific reference to the following complete program
Package Jdbc;import java.sql.*;p ublic final class Jdbcutils {private Jdbcutils () {} private static String URL = "Jdbc:my Sql://localhost:3306/qogir "; private static String username = "root"; private static String password = "root"; /** * Registration drive 1 Left drive jar, unable to compile */* static {try {java.sql.DriverManager.registerDriver (new COM.MYSQL.JDBC . Driver ()); } catch (SQLException e) {e.printstacktrace (); }}*//** * Registered drive mode 3 load Com.mysql.jdbc.Driver recommended way */* static{try {class.forname ("Com.mysql.jdbc.Dri Ver "); } catch (ClassNotFoundException e) {throw new Exceptionininitializererror (e); }}*//** * Registered Drive Mode 2 * Multiple drivers with ":" Delimited * system.setproperty ("Jdbc.drivers", "Com.mysql.jdbc.Driver:oracle.jdbc.driver". Oralcedriver "); */Static {System.setproperty ("jdbc.drivers", "Com.mysql.jdbc.Driver"); /** * Database Connection * JDBC: Sub-Protocol: Sub-name//hostname: Port/Database name There is no sub-name * native, port number is the default port number can be omitted "localhost:3306" Jdbc:mysql:///qogir **/ Public STATic Connection getconnection () throws SQLException {return drivermanager.getconnection (Url,username,password); }/** * Frees resource * * public static void Close (ResultSet rs,statement st,connection con) {if (rs! = null) {try { Rs.close (); } catch (SQLException e) {e.printstacktrace (); }} if (St! = null) {try{st.close (); } catch (SQLException e) {e.printstacktrace (); }} if (con! = null) {try{con.close (); } catch (SQLException e) {e.printstacktrace (); }}}}package jdbc;import java.sql.*;p ublic class Jdbctest {/** * create user */public void Createusers () {Connection conn ection = null; Statement Statement = null; try {connection = jdbcutils.getconnection (); statement = Connection.createstatement (); for (int i=1;i<=10;i++) {String-sql = "INSERT into user (Id,name,password) VALUES (" +i+ ", ' Name ' +i+" ', ' xx ' +i+ "')"; Statement.executeupdate (SQL); }} catch (SQLEXception e) {e.printstacktrace (); }finally {jdbcutils.close (null,statement,connection); }}/** * Update user */public void Updateusers () {Connection Connection = null; Statement Statement = null; try {connection = jdbcutils.getconnection (); statement = Connection.createstatement (); for (int i=1;i<=10;i++) {String sql = "Update user set Name= ' abc" +i+ "' where id=" +i; Statement.executeupdate (SQL); }} catch (SQLException e) {e.printstacktrace (); }finally {jdbcutils.close (null,statement,connection); }}/** * Delete user */public void Deleteusers () {Connection Connection = null; Statement Statement = null; try {connection = jdbcutils.getconnection (); statement = Connection.createstatement (); String sql = "Delete from user where 1=1"; int i = statement.executeupdate (sql); System.out.println ("deleted" +i+ "bar data!) "); } catch (SQLException e) {e.printstacktrace (); }finally {jdbcutils.close (null,statement,connection); }}/** * Read User */puBlic void Readusers () {Connection Connection = null; Statement Statement = null; ResultSet ResultSet = null; try {/** * 2, Establish database connection */connection = jdbcutils.getconnection (); /** * 3, creates a tool class object that sends a simple SQL statement to execute without parameters to the database, based on a database connection already established */statement = connection.createstatement (); /** * 4, send SQL statement to database, get result set */ResultSet = Statement.executequery ("Select Id,name,password from user"); /** * 5, processing result */while (Resultset.next ()) {System.out.println (resultset.getstring ("id") + "---->" +resultset . getString ("name") + "--->" +resultset.getstring ("password"); }} catch (SQLException e) {e.printstacktrace (); }finally {/** * 6, releasing resources */Jdbcutils.close (resultset,statement,connection); }} public static void Main (string[] args) {//new jdbctest (). Createusers (); New Jdbctest (). Updateusers (); New Jdbctest (). Deleteusers (); New Jdbctest (). Readusers (); }}
-
- This article is from: Linux Tutorial Network
Learn more about JDBC (i) – Understanding JDBC