The JDBC maven dependency for MySQL and Oracle are as follows:
<!--MySQL - <Dependency> <groupId>Mysql</groupId> <Artifactid>Mysql-connector-java</Artifactid> <version>5.1.36</version> </Dependency> <!--Oracle - <Dependency> <groupId>Com.oracle</groupId> <Artifactid>Ojdbc7</Artifactid> <version>12.1.0.2</version> </Dependency>
Because of Oracle licensing issues, MAVEN does not provide Oracle JDBC Driver,maven to add Oracle JDBC Dependency method See: Http://www.cnblogs.com/wuyouwulv/p/maven_ Configure_oracle_jdbc.html
Code:
Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;Importjava.util.Date; Public classSqltest {Private StaticString appended_db_info = "?useunicode=true&characterencoding=utf8&rewritebatchedstatements=true& Uselegacydatetimecode=false&servertimezone=asia/shanghai "; Public StaticConnection getmysqlconnection (String dburl, String dbUser, String dbpwd)throwsClassNotFoundException, SQLException {//load the drive, and the following code loads the MySQL driveClass.forName ("Com.mysql.jdbc.Driver"); //registering a MySQL driveDrivermanager.registerdriver (Newcom.mysql.jdbc.Driver ()); //establishing a database connection returnjava.sql.DriverManager.getConnection (Dburl, DbUser, dbpwd); } Public StaticConnection getoracleconnection (String dburl, String dbUser, String dbpwd)throwsClassNotFoundException, SQLException {class.forname ("Oracle.jdbc.driver.OracleDriver"); returnjava.sql.DriverManager.getConnection (Dburl, DbUser, dbpwd); } Public Static voidMain (string[] args) {String Dburl= "Jdbc:mysql://host:port/dbname" +Appended_db_info; String DbUser= "Mysql_username"; String dbpwd= "Mysql_password"; Statement stmt=NULL; ResultSet RS=NULL; //connect to MySQL database Try{Connection con=getmysqlconnection (Dburl, DbUser, dbpwd); stmt=con.createstatement (); RS= Stmt.executequery ("Select id,age,date from User"); while(Rs.next ()) {intproduct_id = Rs.getint (1); intcategories_id = Rs.getint (2); Date date_added= Rs.getdate (3); System.out.println (product_id+ "," + categories_id + "," +date_added); } } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } //connecting to an Oracle databaseDburl = "Jdbc:oracle:thin: @host:p ort:dbname"; DbUser= "Oracle_username"; Dbpwd= "Oracle_password"; Try{Connection con=getoracleconnection (Dburl, DbUser, dbpwd); stmt=con.createstatement (); String SQL= "SELECT Name ID from user"; RS=stmt.executequery (SQL); while(Rs.next ()) {String res= rs.getstring (1); System.out.println (RES); } } Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); } }}
Java connection to MySQL database and Oracle database with simple SQL operation