一、SQLServer
1、sun.jdbc.odbc.JdbcOdbcDriver (Jdbc:Odbc连接桥)
先配置数据源: 用户DSN -> 服务器:(local) 或者 其他IP:XXX.XX.XX.X -> 更改默认数据库为:eeee -> 测试连接成功
测试连接代码:
package SQLServer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestDataSource {
public TestDataSource() {
}
public void connectAndDisconnect() {
try {
System.out.println("Attempting to load the JDBC Driver ...");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("JDBC driver loaded.");
System.out.println("Connecting to database...");
Connection con;
con = DriverManager.getConnection("jdbc:odbc:eeee");
System.out.println("Database connection established.");
System.out.println("Database connection closed");
if (con != null) {
con.close();
}
System.out.println("Database connection closed.");
}
catch (ClassNotFoundException cnfe) {
System.out
.println("ClassNotFoundException:could not locate DB driver");
}
catch (SQLException cnfe) {
System.out.println("SQLException:Database reports an error.");
}
catch (Exception e) {
System.out
.println("An unknown error occurred while connecting to DB.");
}
}
public static void main(String args[]) {
TestDataSource test = new TestDataSource();
test.connectAndDisconnect();
}
}
2、非JDBC:ODBC桥
下载一个驱动,解压后安装后将驱动的路径添加到环境变量classpath中去,就是3个.jar文 件,mssqlserver.jar,msbase.jar,msutil.jar。直接将这3个.jar扔到jdk路径下的lib目录中,然后在 classpath里面添加这3个.jar的真实路径。环境设置完成。
使用类似下面连接实例即可:
public static final String sqlDriver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
public static final String sqlUrl = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=WBBS";
public static final String sqlUsername = "sa";
public static final String sqlPassword = "sa";
Class.forName(sqlDriver);
Connection SQLConnection = DriverManager.getConnection(sqlUrl,sqlUsername,sqlPassword);
Statement stmt=SQLConnection.createStatement();
ResultSet SQLrs=stmt.executeQuery(UpdateSql);
int n=stmt.executeUpdate(InsertSql);
这里有个地址下载驱动
http://download.microsoft.com/download/SQLSVR2000/jdbc/2000/NT45XP/EN-US/setup.exe
常见错误:
没有安装补丁,报错:
org.apache.jasper.JasperException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Connection refused: connect
3、连接SQLServer示例类
....
三、Oracle