1.连接SQL server 2005数据库
public class JDBCConnection {
/**
* DRIVER 数据库驱动
* URL 数据库地址
* USER_NAME 数据库用户名
* PASSWORD 数据库登录密码
*/
private static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String URL="jdbc:sqlserver://localhost:1433;DatabaseName=LibraryManagement";
private static final String USER_NAME="sa";
private static final String PASSWORD="123456";
private static Connection conn;
private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
//通过静态代码块加载JDBC驱动
static
{
try{
Class.forName(DRIVER).newInstance();
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 功能:建立与数据库的连接
* @return Connection的实例
*@throws ClassNotFound,SQLException
*/
public static Connection getConnection()
{
//从线程中获得数据库连接
conn=threadLocal.get();
if(conn==null)
{
try{
conn=DriverManager.getConnection(URL,USER_NAME,PASSWORD);
//将数据库连接保存到线程中
threadLocal.set(conn);
}catch(SQLException e)
{
e.printStackTrace();
}
}
return conn;
}
}
2.连接MySQL数据库
public Connection getConnection() throws ClassNotFoundException {
String url = "jdbc:mysql://localhost:3306/mesdb";
String name = "root";
String passw = "123456";
Class.forName("com.mysql.jdbc.Driver");
try {
Connection conn=DriverManager.getConnection(url,name,passw);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
3.连接Oracle数据库
public OracleJDBC {
public Connection getConnection() throws ClassNotFoundException {
String url = "jdbc:oracle:thin:@192.168.102.243:1521:orcl";
String name = "training"; String passw = "123456";
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
Connection conn =DriverManager.getConnection(url,name,passw);
return conn;
} catch (Exception e)
{
e.printStackTrace();
return null;
}
}