Different databases need to go to the official web site to download the corresponding driver jar, such as MySQL https://dev.mysql.com/downloads/connector/j/
Properties file
1 #MySQL2 MysqlDriver:com.mysql.jdbc.Driver3Mysqlurl:jdbc\:mysql\://localhost\:3306\/test4 Mysqluser:root5 Mysqlpassword:root6 7 #Oracle8 OracleDriver:oracle.jdbc.driver.OracleDriver9Oracleurl:jdbc\:oracle\:[email protected]\:1521\:ORCLTen Oracleuser:username OneOraclepassword:password
1 PackageCom.commonutil;2 3 /**4 * JDBC Tool class5 * @authorAndrew6 */7 8 Importjava.io.IOException;9 Importjava.sql.Connection;Ten ImportJava.sql.DriverManager; One ImportJava.sql.ResultSet; A Importjava.sql.SQLException; - Importjava.sql.Statement; - Importjava.util.Properties; the - Public classJdbcutil { - //can help read and manipulate information in resource files - Private StaticProperties Pros =NULL; + //Static code block, loading config.properties file - Static { +Pros =NewProperties (); A Try { atPros.load (Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream ("./com/config/config.properties")); -}Catch(IOException e) { - e.printstacktrace (); - } - } - in /** - * Build MySQL database connection to * @returnjava.sql.Connection Connection Object + * @throwsclassnotfoundexception - * @throwsSQLException the */ * Public StaticConnection Getmysqlconn ()throwsClassNotFoundException, SQLException { $Class.forName (Pros.getproperty ("Mysqldriver"));Panax Notoginseng returnDrivermanager.getconnection (Pros.getproperty ("Mysqlurl"), Pros.getproperty ("Mysqluser"), -Pros.getproperty ("Mysqlpassword")); the } + A /** the * Establishing an Oracle database connection + * @returnjava.sql.Connection Connection Object - * @throwsclassnotfoundexception $ * @throwsSQLException $ */ - Public StaticConnection Getoracleconn ()throwsClassNotFoundException, SQLException { -Class.forName (Pros.getproperty ("Oracledriver")); the returnDrivermanager.getconnection (Pros.getproperty ("Oracleurl"), Pros.getproperty ("Oracleuser"), -Pros.getproperty ("Oraclepassword"));Wuyi } the - /** Wu * Close all database connections - * @paramRs ResultSet Object About * @paramstmt Statement Object $ * @paramConn Connection Object - * @throwsSQLException - */ - Public voidCloseAll (ResultSet rs, Statement stmt, Connection conn)throwsSQLException { A if(rs! =NULL) + Rs.close (); the if(stmt! =NULL) - Stmt.close (); $ if(Conn! =NULL) the Conn.close (); the } the the //Close ResultSet result set - Public voidClose (ResultSet rs)throwsSQLException { in if(rs! =NULL) { the rs.close (); the } About } the the //Close Statement the Public voidClose (Statement stmt)throwsSQLException { + if(stmt! =NULL) { - stmt.close (); the }Bayi } the the //Close Database Connection connection object - Public voidClose (Connection conn)throwsSQLException { - if(Conn! =NULL) { the conn.close (); the } the } the}
Java connects to the database using JDBC