Java defines a standard interface and class for JDBC, which provides a uniform way for programmers to manipulate databases.
Download the jar package for the corresponding database and add it to the project.
JDBC operates in a single way, consisting of five processes:
1. Register the database driver with the JDBC Class library provided by the database vendor to the DriverManager
2. Connect to the database using the Getconnection () method provided by the DriverManager
3. Establishing an SQL statement object through the Createstatement method of the Connection object of the database
4. Execute the SQL statement and return the result collection to ResultSet
5. Using the while loop to read the results
6. Closing Database Resources
Code examples
1 Importjava.sql.Connection;2 ImportJava.sql.DriverManager;3 ImportJava.sql.ResultSet;4 Importjava.sql.SQLException;5 Importjava.sql.Statement;6 7 Public classTestjdbc8 {9 Private Final StaticString url = "Jdbc:mysql://localhost:3306/test";Ten One Private Final StaticString user = ""; A - Private Final StaticString Password = ""; - the Public Static voidMain (string[] args) - { -ResultSet rs =NULL; -Statement stmt =NULL; + - //JDBC Driver loading + Driverloader (); A //Get database connection atConnection conn =connectionget (); - Try - { -stmt =conn.createstatement (); -String sql = "SELECT * FROM LJF"; -rs =stmt.executequery (SQL); in while(Rs.next ()) - { toSystem.out.print (Rs.getint ("id") + ""); +System.out.print (rs.getstring ("name") + ""); - } the } * Catch(SQLException e) $ {Panax NotoginsengSYSTEM.OUT.PRINTLN ("Data manipulation error"); - e.printstacktrace (); the } + finally A { the //Close the database + Close (RS, stmt, conn); - } $ } $ - Private Static voidDriverloader () - { the Try - {WuyiClass.forName ("Com.mysql.jdbc.Driver");//load MySQL driver the } - Catch(classnotfoundexception e) Wu { -SYSTEM.OUT.PRINTLN ("Driver load Error"); About e.printstacktrace (); $ } - } - - Private StaticConnection connectionget () A { +Connection conn =NULL; the Try - { $conn =drivermanager.getconnection (URL, user, password); the } the Catch(SQLException e) the { theSYSTEM.OUT.PRINTLN ("Database link Error"); - e.printstacktrace (); in } the returnConn; the } About the Private Static voidClose (ResultSet rs, Statement stmt, Connection conn) the { the Try + { - if(rs! =NULL) the {Bayi rs.close (); thers =NULL; the } - if(stmt! =NULL) - { the stmt.close (); thestmt =NULL; the } the if(Conn! =NULL) - { the conn.close (); theconn =NULL; the }94 } the Catch(Exception e) the { theSYSTEM.OUT.PRINTLN ("Database shutdown error");98 e.printstacktrace (); About } - }101}
Java Learning (14): JDBC Mode Connection Database Example