MySQL和Oracle的JDBC的maven dependency如下:
<!-- 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>
由于Oracle授权问题,Maven不提供Oracle JDBC driver,maven添加oracle jdbc依赖的方法见:http://www.cnblogs.com/wuyouwulv/p/maven_configure_oracle_jdbc.html
代码:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; public class SQLTest { private static String APPENDED_DB_INFO = "?useUnicode=true&characterEncoding=UTF8&rewriteBatchedStatements=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai"; public static Connection getMySQLConnection(String dbUrl, String dbUser, String dbPwd) throws ClassNotFoundException, SQLException { // 加载驱动器,下面的代码为加载MySQL驱动器 Class.forName("com.mysql.jdbc.Driver"); // 注册MySQL驱动器 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 建立数据库连接 return java.sql.DriverManager.getConnection(dbUrl, dbUser, dbPwd); } public static Connection getOracleConnection(String dbUrl, String dbUser, String dbPwd) throws ClassNotFoundException, SQLException { Class.forName("oracle.jdbc.driver.OracleDriver"); return java.sql.DriverManager.getConnection(dbUrl, dbUser, dbPwd); } public static void main(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; // 连接MySQL数据库 try { Connection con = getMySQLConnection(dbUrl, dbUser, dbPwd); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT id,age,date FROM user"); while(rs.next()) { int product_id = rs.getInt(1); int categories_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(); } // 连接Oracle数据库 dbUrl = "jdbc:oracle:thin:@host:port: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(); } } }
时间: 2024-10-10 01:56:05