mysql-connector-java-3.1.12-bin.jar置於JDK的/jre/lib/ext目錄下
try
{
// 鏈接字符串
String connName = "jdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=gb2312";
// 登陸用戶名
String dbUser = "root";
// 登陸密碼
String dbPwd = "zhihua1124";
Class.forName("com.mysql.jdbc.Driver");
// 生成一個鏈接
Connection con = DriverManager.getConnection(connName, dbUser, dbPwd);
return con;
}catch(Exception e)
{
System.err.println("Connection the database is wrong !!");
return null;
}
2 Java鏈接SQL Server 2005
下載sqljdbc.jar置於JDK的/jre/lib/ext目錄下
try
{
// 鏈接字符串
String connName = "jdbc:sqlserver://localhost:1433;integratedSecurity=true;databaseName=sqlserverdb";
// 登陸用戶名
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //2005
// Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");//2000
// 生成一個鏈接
Connection con = DriverManager.getConnection(connName);
return con;
}catch(Exception e)
{
e.printStackTrace();
return null;
}
3 Java鏈接Access
創建ODBC數據源,此處爲accessdb
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:accessdb");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
int id = Integer.parseInt(rs.getString("id"));
String name = rs.getString("name");
String address = rs.getString("address");
String phone = rs.getString("phone");
String email = rs.getString("email");
StudentInfo stu = new StudentInfo(id,name,address,phone,email);
allStudent.add(stu);
}
rs.close();
stmt.close();
return allStudent;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
4 Java鏈接Oracle
在Oracle的安裝目錄之中/Db_1/jdbc/lib找到classes12.jar,置於JDK的/jre/lib/ext目錄下
同時在/Db_1/jdbc/lib解壓classes12.zip,比方解壓至D:/classes12,在環境變量classpath中添加
try
{
String name="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@localhost:1521:oracledb";
Class.forName(name).newInstance();
Connection con=DriverManager.getConnection(url,"ddbi","ddbi");
return con;
}catch(Exception e)
{
e.printStackTrace();
return null;
}java
原文地址:http://blog.csdn.net/zhihua1124/article/details/3309937mysql