Java Program Access database:
1. Get the driver provided by the database vendor (Implementation class for the JDBC interface)
such as Ojdbc14.jar--Oracle database driver jar Package
Mysql-connector-java-5.1.8-bin.jar--mysql database driver jar Package
You can download it online.
2. Use the JDBC API to access the database
Connections,SQL statement execution, results
Java.sql.Driver: Each database vendor needs to implement this interface, the driver's tag
Java.sql.Connection: Encapsulation and database connection
Java.sql.Statement: Encapsulation of SQL statements to execute
Java.sql.ResultSet: Encapsulates the result set of a query
3. JDBC Programming steps
step1--Load Driver
step2--Getting a Connection object
step3--Executing SQL statements
step4--Processing Result Sets
step5--Closing Resources
4, the following gives the Connection database tool class (oneself writes the connection MySQL database, if wants to connect the oeacle can modify the corresponding parameter)
Packagecom.day03;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;Importjava.util.Properties; Public classConnectionutils {//Threading Single Example Private Staticthreadlocal<connection> TL =NewThreadlocal<connection>(); Private StaticString URL; Private StaticString driver; Private StaticString username; Private StaticString password; Static{Properties props=NewProperties (); Try { //The dependency file reads the database configuration information to load the configuration file as a class loadprops.load (connectionutils.class. getClassLoader (). getResourceAsStream ("Com/day03/db_mysql.properties")); } Catch(IOException e) {}if(Props! =NULL) {URL= Props.getproperty ("url"); Driver= Props.getproperty ("Driver"); Username= Props.getproperty ("username"); Password= Props.getproperty ("Password"); //mount and register the database driver Try{class.forname (driver); } Catch(ClassNotFoundException e) {e.printstacktrace (); } } } Public StaticConnection getconnection ()throwsSQLException {Connection con=Tl.get (); if(Con = =NULL) {con=drivermanager.getconnection (URL, username, password); Tl.set (con); } returncon; } Public Static voidCloseConnection () {Connection con=Tl.get (); Try { if(Con! =NULL) {con.close (); Tl.set (NULL); } } Catch(SQLException e) {e.printstacktrace (); } } Public Static voidclosestatement (Statement stmt) {Try { if(stmt! =NULL) {stmt.close (); } } Catch(SQLException e) {e.printstacktrace (); } } Public Static voidCloseresultset (ResultSet rs) {Try { if(rs! =NULL) {rs.close (); } } Catch(SQLException e) {e.printstacktrace (); } } Public Static voidCloseAll (Statement stmt, ResultSet rs) {closeconnection (); Closestatement (stmt); Closeresultset (RS); } Public Static voidMain (string[] args)throwsexception{System.out.println (Connectionutils.getconnection ()); }}
5. Configuration parameter File Db_mysql.properties
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testusername=Rootpassword =root
6. DAO mode operation database here is the code example
1) Emp.java
//entity class Public classEMP {Private intID; PrivateString name; Private Doublesalary; Public intgetId () {returnID; } @Override PublicString toString () {return"Emp [id=" + ID + ", name=" + name + ", salary=" + salary + "]"; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public Doublegetsalary () {returnsalary; } Public voidSetsalary (Doublesalary) { This. Salary =salary; } PublicEMP (intID, String name,Doublesalary) { Super(); This. ID =ID; This. Name =name; This. Salary =salary; } PublicEmp () {Super(); } PublicEMP (String name,Doublesalary) { Super(); This. Name =name; This. Salary =salary; }}
2) DAO Interface class
Import java.util.List; Public Interface Empdao { Listthrows Exception;}
3) Factory class
Public class empdaofactory { // reads the class name of the implemented class in the file, instantiates public static by reflection Empdao Getempdao () { returnnew empdaomysql ();} }
4) DAO Interface implementation class
Public classEmpdaomysqlImplementsempdao{ Public Static FinalString find_all_emp = "SELECT * from T_emp";//Query Statements PublicList<emp> findallemp ()throwsexception{List<Emp> emplist =NewArraylist<emp>(); Connection Conn=connectionutils.getconnection (); PreparedStatement stmt=conn.preparestatement (find_all_emp); ResultSet RS=Stmt.executequery (); while(Rs.next ()) {intid = rs.getint (1); String name= Rs.getstring (2); DoubleSalary = rs.getdouble (3); EMP EMP=NewEmp (ID, name, salary); Emplist.add (EMP); } connectionutils.closeall (stmt, RS); returnemplist; }}
5) Test class
Public class empbiz { publicstaticvoidthrows exception{ = Empdaofactory.getempdao (); List<Emp> emplist = dao.findallemp (); for (Emp e:emplist) { System.out.println (e); }}}
The basic implementation of the DAO mode through the JDBC operation database.
Java DAO mode connects to database through JDBC