Job content: During project development this week, I contacted JDBC (Java Data Base Connectivity,java database connection), a Java API for executing SQL statements that provides unified access to a variety of relational databases. It consists of a set of classes and interfaces written in the Java language. JDBC can provide unified access to a variety of databases, in short, JDBC is used to connect Java and the database bridge, embodies the Java "write once, run everywhere" of the tall spirit. After connecting to the Oracle database, I was instructed by my classmates to learn http://www.imooc.com/video/4387 JDBC video and simply completed part of our team project.
Here is my first step in learning jdbc, so I want to elaborate on the process of using JDBC to connect to an Oracle database.
JDBC Connection Database
Create a program that connects to the database in JDBC with the following 7 steps:
1. Load the JDBC driver
Before connecting to a database, you first load the driver of the database you want to connect to the JVM (Java Virtual machine), which is implemented by the static method forname (String className) of the Java.lang.Class class.
1 try {// load MySQL driver class 2 3 class.forname ("Com.mysql.jdbc.Driver" ); 4 5 }catch (ClassNotFoundException e) { 6 7 System.out.println ("Driver class not found, load driver failed!") "); 8 9 E.printstacktrace (); 10 11 }
after a successful load, an instance of the driver class is registered in the DriverManager class.
2. Provide the URL of the JDBC connection
(1) The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.
(2) Writing form: Protocol: Sub-Protocol: Data source identification
Protocol: Always start with JDBC in JDBC
Sub-Protocol: A bridge-connected driver or database management system name.
Data source identification: The tag locates the address of the database source and the connection port.
For example: (MySQL connection URL) jdbc:mysql:
LOCALHOST:3306/TEST?USEUNICODE=TRUE&CHARACTERENCODING=GBK;
Useunicode=true: Indicates the use of the Unicode character set. If Characterencoding is set to gb2312 or GBK, this parameter must be set to true . CHARACTERENCODING=GBK: The character encoding method.
3. Create a connection to the database
(1) to connect to a database, you need to request and obtain a connection object from Java.sql.DriverManager, which represents a connection to a database.
(2) Use DriverManager's Getconnectin (string URL, string username, string password) method to pass in the path of the specified database to be connected, the user name of the database, and the password to obtain.
1 //connect to MySQL database, user name and password are root2String url = "Jdbc:mysql://localhost:3306/test" ; 3String username = "root" ; 4String password = "root" ; 5 Try{ 6Connection con =7 drivermanager.getconnection (URL, username, password); 8}Catch(SQLException se) {9SYSTEM.OUT.PRINTLN ("Database connection failed! "); Ten Se.printstacktrace (); One}
4. Create a statement
1, execute static SQL statements. Typically implemented through statement instances.
2, execute dynamic SQL statements. Typically implemented through PreparedStatement instances.
specific implementation:
Statement stmt = Con.createstatement ();
PreparedStatement pstmt = con.preparestatement (sql);
callablestatement cstmt = Con.preparecall ("{Call Demosp (?,?)}");
5. Execute SQL statements
The statement interface provides three ways to execute SQL statements: ExecuteQuery, executeupdate, and execute
1. ResultSet executeQuery (String sqlString): Executes the SQL statement that queries the database and returns a result set (ResultSet) object.
2, int executeupdate (String sqlString): Used to execute INSERT, UPDATE, or DELETE statements and SQL DDL statements such as CREATE table and drop table, etc.
3. Execute (sqlString): Used to execute statements that return multiple result sets, multiple update counts, or both.
Specific implementation code:
ResultSet rs = stmt.executequery ("SELECT * from ...");
int rows = Stmt.executeupdate ("INSERT into ...");
Boolean flag = Stmt.execute (String sql);
6. Processing Results
Two cases:
1. The number of records affected by this operation is returned by performing the update.
2. The result of executing the query returned is a ResultSet object.
ResultSet contains all rows that conform to the conditions in the SQL statement, and it provides access to the data in those rows through a set of Get methods.
get data using the access method of the result set (ResultSet) object:
1 while 2 String name = rs.getstring ("name"3//4
(columns are numbered from left to right and start with column 1)
7. Close the JDBC object
all JDBC objects used are closed after the operation is complete to release the JDBC resource, turn off order Harmony The opposite of the Ming Order:
1. Close record set 2. Closing the statement 3. Close the Connection object
11if(rs! =NULL){//To close a record set22Try{ 33rs.close ();44}Catch(SQLException e) {55e.printstacktrace ();66 } 77 } 88if(stmt! =NULL){//Close Declaration99Try{ Ten10stmt.close (); One11}Catch(SQLException e) { A12e.printstacktrace (); -13 } -14 } the15if(Conn! =NULL){//Close the Connection object -16Try{ -17conn.close (); -18}Catch(SQLException e) { +19e.printstacktrace (); -20 } +21}
The complete code is as follows: If the connection is successful, the names of all employees in the employee table will appear
1 ImportJava.sql.*;2 Public classTest {3 Public Static voidMain (string[] args) {4ResultSet rs =NULL;5Statement stmt =NULL;6Connection conn =NULL;7 Try {8Class.forName ("Oracle.jdbc.driver.OracleDriver");9 //new Oracle.jdbc.driver.OracleDriver ();Tenconn =Drivermanager.getconnection ( One"Jdbc:oracle:thin: @localhost: 1521:xe", "HR", A"Oracle"); -stmt =conn.createstatement (); -rs = Stmt.executequery ("SELECT * FROM Employees"); the while(Rs.next ()) { -System.out.println (rs.getstring ("First_Name")); - //System.out.println (Rs.getint ("Deptno")); - } +}Catch(ClassNotFoundException e) { - e.printstacktrace (); +}Catch(SQLException e) { A e.printstacktrace (); at}finally { - Try { - if(rs! =NULL) { - rs.close (); -rs =NULL; - } in if(stmt! =NULL) { - stmt.close (); tostmt =NULL; + } - if(Conn! =NULL) { the conn.close (); *conn =NULL; $ }Panax Notoginseng}Catch(SQLException e) { - e.printstacktrace (); the } + } A } the}
View Code
Software Quality assurance and testing sixth week work