public class DBTest { public static void main(String[] args) { //jdbc驱动 String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver"; //连接服务器和数据库shopping String dbURL="jdbc:sqlserver://192.168.1.33:1433;DatabaseName=shopping"; String userName="sa"; String userPwd="tiger"; Connection connection; try { //加载驱动 Class.forName(driverName); //获取连接 connection=DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("Connection SQLServer Successful!"); } catch (Exception e) { e.printStackTrace(); } } }
注:
1.因为SQLexpress服务器默认是禁用的并且端口号没有配置,所以要进行重新设置
2.如果你以前用java连接sql server 2000的话就要注意了:
在sql server 2000 中加载驱动和URL路径的语句是
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample";
而sql server 2005 中加载驱动和url的语句则为
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";
如果写法错误将会找不到驱动.