日期:2014-05-16 浏览次数:20496 次
?
?
用于:java使用jdbc连接不同数据
注: 1.版本:mysql5.5, oracle11g,derby 2.附件:另附连接各种数据立库的驱动(注:derby后续再谈)
?
实例代码在下:
?
package com.qingshan.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.apache.log4j.Logger; /** * <pre> * 得到一个数据连接(connect) * </pre> * <hr Color="green" ></hr> * 2012 Qingshan Group 版权所有 * <hr Color="green" ></hr> * @author thetopofqingshan * @version 1.0.0 * @since JDK 1.5 * @date 2012-3-29 */ public class DatabasesConnect{ private static Logger logger = Logger.getLogger(DatabasesConnect.class.getName()); /*数据库连接的开头*/ public final static String url_mysql = "jdbc:mysql://"; public final static String url_oracle = "jdbc:oracle:thin:@"; public final static String url_derby = "jdbc:derby:"; /*数据库驱动名*/ public final static String driverName_oracle = "oracle.jdbc.driver.OracleDriver"; public final static String driverName_mysql = "com.mysql.jdbc.Driver"; public final static String driverName_derby = "org.apache.derby.jdbc.EmbeddedDriver"; /** * 所操作的数据库名称 */ public static String databaseName = "temp"; /** * 数据库所有机器的ip */ public static String ip = "localhost"; /** * 数据库登陆用户 */ public static String name = "sys as sysdba"; /** * 数据库登陆密码 */ public static String password = "qingshan"; /** * 构造oracle连接 */ public static final int oracle = 1; /** * 构造oracle连接 */ public static final int mysql = 0; /** * 构造derby连接 */ public static final int derby = 2; /** * 创建数据连接实例 */ private static Connection conn = null; /** * <pre> * 得到一个数据连接(connect) * </pre> * @param pattern 数库类型 * @return 数据库连接 * @throws ClassNotFoundException 数据库驱动包未找到 * @throws SQLException 构造数据库连接实例发生错误 * */ public static Connection getConnection(int pattern) throws ClassNotFoundException, SQLException{ //保证数据库连接为单例 if(conn != null){ return conn; } StringBuffer url = new StringBuffer();//拼接不同参数 String driverName = null; if(pattern == 1){ //jdbc:oracle:thin:@localhost:1521:qingshan url.append(url_oracle); url.append(ip); url.append(":1521:"); url.append(databaseName); driverName = driverName_oracle; logger.info("connnecting to oracle ...."); }else if(pattern == 0){ url.append(url_mysql); url.append(ip); url.append(":3306/"); url.append(databaseName); driverName = driverName_mysql; logger.info("connnecting to mysql ...."); }else if(pattern == 2){ url.append(url_derby); url.append(databaseName+""); driverName = driverName_derby; logger.info("connnecting to derby ...."); } Class.forName(driverName); conn = DriverManager.getConnection(url.toString(), name, password); //数据库单例 return conn; } }
转载注明原文地址:http://thetopofqingshan.iteye.com/admin/blogs/1504004