1.准备工作: 准备相关的软件(Eclipse除外,开源软件可以从官网下载)
<1>.Microsoft SQL server 2005 Express Edition
下载地址:http://download.microsoft.com/download/0/9/0/09020fab-d2c3-4a8c-b9e0-db53a7a30ae8/SQLEXPR_CHS.EXE
<2>.SQL Server Management Studio
下载地址:http://www.microsoft.com/downloads/details.aspx"htmlcode">
import java.sql.*; public class Test { public static void main(String[] srg) { String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动 String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample"; //连接服务器和数据库sample String userName = "sa"; //默认用户名 String userPwd = "123456"; //密码 Connection dbConn; try { Class.forName(driverName); dbConn = DriverManager.getConnection(dbURL, userName, userPwd); System.out.println("Connection Successful!"); //如果连接成功 控制台输出Connection 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"; 如果写法错误将会找不到驱动.