1. Database Link class
1 Importjava.sql.Connection;2 ImportJava.sql.DriverManager;3 Importjava.sql.SQLException;4 5 Public classDBHelper {6 /**7 * Get Database link8 * 9 * @returnDatabase LinksTen */ One Public StaticConnection getconnection () { AConnection conn =NULL; -String Driver = "Com.microsoft.sqlserver.jdbc.SQLServerDriver";//Drive -String username = "sa";//User name theString password = "sa";//Password -String url = "Jdbc:sqlserver://192.168.1.10;databasename=test";//SQL Server link address - Try { -Class.forName (driver);//Load driver class +conn =drivermanager.getconnection (URL, username, password); -}Catch(ClassNotFoundException e) { +System.out.println ("Driver class not found, load driver failed!") "); A e.printstacktrace (); at}Catch(SQLException e) { -SYSTEM.OUT.PRINTLN ("Database connection failed! "); - e.printstacktrace (); - } - returnConn; - } in -}
2. Execute the query
1 Importjava.sql.Connection;2 Importjava.sql.PreparedStatement;3 ImportJava.sql.ResultSet;4 Importjava.sql.SQLException;5 6 Public classTestquery {7 8 Public Static voidMain (string[] args) {9Connection conn = Dbhelper.getconnection ();//Get Database linkTenPreparedStatement PS =NULL; OneResultSet rs =NULL; A Try { -String sql = "SELECT * from Users"; -PS =conn.preparestatement (SQL); thers = Ps.executequery ();//Execute Query - while(Rs.next ()) {//determine if there is still the next data -SYSTEM.OUT.PRINTLN ("ID:" + rs.getstring ("id") + "\tname:" -+ rs.getstring ("name")); + } -}Catch(SQLException e) { + e.printstacktrace (); A}finally { at if(rs! =NULL) { - Try { -Rs.close ();//To close a record set -}Catch(SQLException e) { - e.printstacktrace (); - } in } - if(PS! =NULL) { to Try { +Ps.close ();//Close Declaration -}Catch(SQLException e) { the e.printstacktrace (); * } $ }Panax Notoginseng if(Conn! =NULL) { - Try { theConn.close ();//Close Connection +}Catch(SQLException e) { A e.printstacktrace (); the } + } - } $ $ } - -}
3. Implementation results
id:00027c20dad4467180be4637d1f6008f Name: Zhang San id:0c99ddbeba304596ae87f34cfb1e21f7 name: John Doe