java连接MySql和Oracle简单实现
来源:互联网 发布:京东金融 人工智能 编辑:程序博客网 时间:2024/06/05 07:01
import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class MySqlDbManager { private static MySqlDbManager instance = null; private MySqlDbManager(){} public static MySqlDbManager getInstance(){ if(null ==instance){ instance = new MySqlDbManager(); } return instance; } public Connection getConnection() { Connection connection = null; String url = "jdbc:mysql://localhost/test"; String usr = "root"; String pwd = "123456"; String driver ="com.mysql.jdbc.Driver"; try { Class.forName(driver); connection =DriverManager.getConnection(url, usr, pwd); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return connection; }}
/** * @author HU-XU *数据库工具类 */public class ToolDButil {static{try {Class.forName("oracle.jdbc.driver.OracleDriver");//"com.mysql.jdbc.Driver"} catch (ClassNotFoundException e1) {e1.printStackTrace();}}//返回连接public static Connection getConnection(){String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";//"jdbc:mysql://localhost/test?user=root&password=root"String userid = "scott";String password = "huxu";Connection conn=null;try {conn=DriverManager.getConnection(jdbcUrl, userid, password);} catch (SQLException e) {e.printStackTrace();}return conn; }//释放连接资源public static void free01(Connection cn,Statement st,ResultSet rs){try {if(rs!=null) rs.close();if(st!=null) st.close();if(cn!=null) cn.close();} catch (SQLException e) {e.printStackTrace();}}public static void free02(PreparedStatement ps, Connection cn){try {if(ps!=null) ps.close();if(cn!=null) cn.close();} catch (SQLException e) {e.printStackTrace();}}}