PackageCom.mybatisLearn.jdbcDao;Importjava.sql.*;classBasedao {//urlprivate staticString URL ="Jdbc:mysql://127.0.0.1:3306/test_data"; Usernameprivate staticString UserName ="Root"; Passwordprivate staticString userpwd ="165177"; PublicConnection Conn () {//database connection initialization Connection con =NULL;Try{Class.forName ("Com.mysql.jdbc.Driver");
6 driver package above: com.mysql.jdbc.cj.Driver con = drivermanager.getconnection (URL, userName, userpwd); }Catch(SQLException e) {System. out. println ("Database connection failed. ");
E.printstacktrace (); }Catch(ClassNotFoundException e) {System. out. println ("Driver class not found, load driver failed." ");
E.printstacktrace (); } returnCon }//Close resource methodPublic voidClose (ResultSet RS, PreparedStatement stmt, Connection conn) {if(Rs!=NULL) {//closing recordsetsTry{Rs.close (); System. out. println ("Recordset closed. "); }Catch(SQLException e) {System. out. println ("Recordset shutdown failed. ");
E.printstacktrace (); }
}if(stmt!=NULL) {//Close declarationTry{Stmt.close (); System. out. println ("preprocessing shutdown. "); }Catch(SQLException e) {System. out. println ("preprocessing shutdown failed. ");
E.printstacktrace (); }
}if(Conn!=NULL) {//Close Connection objectTry{Conn.close (); System. out. println ("Database shutdown. "); }Catch(SQLException e) {System. out. println ("Database shutdown failed. ");
E.printstacktrace (); }}//Query TestPublic voidTest ()throwsSQLException {Basedao BD =NewBasedao ();
Connection con = bd.conn (); String sql =the Select*From user ";
Precompiled PreparedStatement Pre = con.preparestatement (SQL); Result set ResultSet res = pre.executequery (SQL); while(Res.next ()) {System. out. println ("["+res.getstring (1) +":" + res.getstring (2) +":" + res.getstring (3) +":" + res.getstring (4) +":"+ res.getstring (5) +"]"); } bd.close (Res,pre,con); Not close database in actual developmentPublic static voidMain (string[] args)throwsSQLException {Basedao BD =NewBasedao ();
Bd.test (); }/* Example database table CREATE table ' user ' (' id ' int (one) not NULL auto_increment, ' username ' varchar
Null COMMENT ' user name ', ' birthday ' date default null COMMENT ' birthday ', ' Sex ' char (1) DEFAULT null COMMENT ' sex ', ' Address ' varchar (256) DEFAULT NULL COMMENT ' addresses ', PRIMARY KEY (' id ') Engine=innodb auto_incremen t=27 DEFAULT charset=utf8;*//* Run results: [1: Harry: 2014-07-10:2: Beijing] [10: John: 2014-07-10:1: Beijing] [16: Zhang Xiaoming: 2014-0
7-10:1: Henan Zhengzhou] [22: Chen Xiaoming: 2014-07-10:1: Henan Zhengzhou] [24: Zhang: 2014-07-10:1: Henan Zhengzhou] [25: Chen Xiaoming: 2014-07-10:1: Henan Zhengzhou]
[26: Harry: 2014-07-10:2: Henan Zhengzhou] the recordset closes.
preprocessing shutdown.
Database shutdown. */