现在的位置: 首页 > 综合 > 正文

在Eclipse中用JDBC连接Sql Server 2005总结

2018年06月30日 ⁄ 综合 ⁄ 共 2265字 ⁄ 字号 评论关闭

* 最近因为开发活动需要,用上了Eclipse,并要求使用精简版的SQL(即 2005)来进行开发项目 * 

1.准备工作: 准备相关的软件(Eclipse除外,开源软件可以从官网下载) 

<1>.Microsoft 2005 Express Edition 

下载地址:http://download.microsoft.com/download/0/9/0/09020fab-d2c3-4a8c-b9e0-db53a7a30ae8/SQLEXPR_CHS.EXE 

<2>. Management Studio 

下载地址:http://www.microsoft.com/downloads/details.aspx?displaylang=zh-cn&FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796#filelist 

<3>. 2005 driver for JDBC 

下载地址:http://download.microsoft.com/download/8/B/D/8BDABAE2-B6EA-41D4-B903-7916EF3690EF/sqljdbc_1.2.2323.101_enu.exe 

2.都下载完之后开始进行安装 ,前两个是属于数据库软件,正常安装即可(注意登陆不要使用windows验证) 

<1> 将JDBC解压缩到任意位置,比如解压到C盘program files下面,并在安装目录里找到sqljdbc.jar文件,得到其路径开始配置环境变量 

在环境变量classpath 后面追加 C:/Program Files/Microsoft 2005 JDBC Driver/sqljdbc_1.2/enu/sqljdbc.jar 

<2> 设置SQLEXPRESS服务器: 

    a.打开 Configuration Manager -> SQLEXPRESS的协议 -> TCP/IP  

    b.右键单击启动TCP/IP  

    c.双击进入,把IP地址中的IP all中的TCP端口设置为1433 

    d.重新启动 2005服务中的SQLEXPRESS服务器 

    e.关闭 Configuration Manager 

<3> 打开刚刚安装好的 Management Studio,连接SQLEXPRESS服务器, 新建,起名字为sample  

<4> 打开Eclipse 

    a.新建工程-> java -> project,起名为Test  
   
    b.选择eclipse->窗口->首选项->->installed JRE  编辑已经安装好的jdk,查找目录添加sqljdbc.jar 

    c.右键单击目录窗口中的Test, 选择Build Path ->Configure Build Path..., 添加扩展jar文件,即把sqljdbc.jar添加到其中 

<5> 编写代码来测试连接  

程序代码:  

import .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.如果你以前用连接 2000的话就要注意了: 

在 2000 中加载驱动和URL路径的语句是 

String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; 
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample"; 

而 2005 中加载驱动和url的语句则为 

String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";  

如果写法错误将会找不到驱动. 

抱歉!评论已关闭.