Jar Package Required: Ddbstoolkit-mysql-1.0.0-bate2.jar
Commons-dbcp-1.4.jar
Configuration file: Mysql-dbcp.properties
Configuration file Contents:
Driver=com.mysql.jdbc.driver
Url=jdbc:mysql://localhost:3306/testdatabase
User=root
pwd=1234
Initsize=1
Maxsize=1
1 PackageConnectdatabase.jdbc;2 3 Importjava.sql.Connection;4 ImportJava.sql.ResultSet;5 Importjava.sql.SQLException;6 Importjava.util.Properties;7 8 ImportOrg.apache.commons.dbcp.BasicDataSource;9 Ten Public classTESTJDBC { One //Create a connection pool A Private StaticBasicdatasource ds; - Static{ -Properties p =NewProperties (); the Try { - //Load configuration file -P.load (TESTJDBC.class. getClassLoader (). getResourceAsStream ("Mysql-dbcp.properties")); -String Driver = p.getproperty ("Driver"); +String url = p.getproperty ("url"); -String user = P.getproperty ("User"); +String Password = p.getproperty ("Password"); AString initsize = P.getproperty ("Initsize"); atString maxSize = P.getproperty ("MaxSize"); - //Load Driver -DS =NewBasicdatasource (); - ds.setdriverclassname (driver); - ds.seturl (URL); - ds.setusername (user); in Ds.setpassword (password); -Ds.setinitialsize (NewInteger (initsize)); toDs.setmaxactive (NewInteger (maxSize)); +}Catch(Exception e) { - e.printstacktrace (); the Throw NewRuntimeException ("load config file failed", e); * } $ }Panax Notoginseng /** - * Get database connection the * @returnConnection + * @throwsSQLException A */ the + Public StaticConnection getconnection ()throwssqlexception{ - returnds.getconnection (); $ } $ /** - * Close Database connection - * @paramConnection the */ - Public Static voidcloseconnection (Connection Connection) {Wuyi if(Connection! =NULL){ the Try { - connection.close (); Wu}Catch(Exception e) { - e.printstacktrace (); About Throw NewRuntimeException ("Close Connection Failed", e); $ } - } - } - /** A * Test + * @paramargs the * @throwsSQLException - */ $ Public Static voidMain (string[] args)throwsSQLException { theConnection Connection =testjdbc.getconnection (); theString sql = "SELECT * FROM Cn_activity"; theJava.sql.Statement s =connection.createstatement (); theResultSet r =s.executequery (SQL); - while(R.next ()) { inString a = r.getstring (1); theString B = r.getstring (2); theString C = r.getstring (3); AboutString d = r.getstring (4); theSystem.out.println (A + "|" +b+ "|" +c+ "|" +d); the } the } +}View Code
DBCP connecting MySQL Database