注册 登录
编程论坛 SQL Server论坛

Java连接SQL Server 2000的两种方法

Ethip 发布于 2008-01-22 20:21, 985 次点击

提示:More details in [url=http://bbs.bccn.net/thread-197935-1-1.html]http://bbs.bccn.net/thread-197935-1-1.html[/url]

方法一、Jdbc-Odbc桥 连接
方法二、JDBC Driver连接(或称非Jdbc-Odbc桥连接)

驱动加载和连接测试实例
/*Jdbc-Odbc桥 连接*/
package connectionTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcOdbcBridgeConnection {
 public static void main(String[] args) {
  // jdbc-odbc桥 连接方式
  String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
  String c ;
  Connection dbConn;
  try {//测试驱动程序加载是否成功
   Class.forName( driverName );
   System.out.println("Driver load Successful ");
  }
  catch(java.lang.ClassNotFoundException e ){
   System.err.print("Class Not Found Exception:");
   //getMessage()的功能:Returns the detail message string of this throwable.
   System.err.println(e.getMessage() );
  }
  try{//测试数据库连接是否成功
   dbConn = DriverManager.getConnection(connection);
   System.out.println("Connection Successful!");
   dbConn.close();
  }
  catch(SQLException e) {
   System.err.println("SQLException: " + e.getMessage());
  }
 }
}



/*JDBC Driver连接*/
package connectionTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class JdbcDriverConnection {
 public static void main(String[] args) {
  // JDBC Driver 连接方式
  String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
  String dbURL = "jdbc:microsoft:sqlserver://127.0.0.1:1433; DatabaseName=pubs";
  String userName = "ethip";
  String userPwd = "ethip";
  Connection dbConn;
  try {//测试驱动程序加载是否成功
   Class.forName( driverName );
   System.out.println("Driver load Successful ");
  }
  catch(java.lang.ClassNotFoundException e ){
   System.err.print("Class Not Found Exception:");
   //getMessage()的功能:Returns the detail message string of this throwable.
   System.err.println(e.getMessage() );
  }
  try{//测试数据库连接是否成功
   dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
   System.out.println("Connection Successful!");
   dbConn.close();
  }
  catch(SQLException e) {
   System.err.println("SQLException: " + e.getMessage());
  }
  

}
}


0 回复
1