JAVA连接SQL2005代码!

// Create a variable for the connection string.
    String connectionUrl = "jdbc:sqlserver:// NIUNAN//EXPRESS: 4954;"
      + "databaseName=pubs;user=sa;password=123456";

    // Declare the JDBC objects.
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
     // Establish the connection.
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     con = DriverManager.getConnection(connectionUrl);
     out.print(con.toString()+"<br />");
    
     // Create and execute an SQL statement that returns some data.
           String SQL = "SELECT TOP 10 * FROM titles";
           stmt = con.createStatement();
           rs = stmt.executeQuery(SQL);

           // Iterate through the data in the result set and display it.
           while (rs.next()) {
              out.println(rs.getString(1) + " " + rs.getString(2)+"<br />");
           }
    
    }

    // Handle any errors that may have occurred.
    catch (Exception e) {
     e.printStackTrace();
    } finally {
     if (rs != null)
      try {
       rs.close();
      } catch (Exception e) {
      }
     if (stmt != null)
      try {
       stmt.close();
      } catch (Exception e) {
      }
   
     if (con != null)
      try {
       con.close();
      } catch (Exception e) {
      }
    }

  有几点要注意的地方,蓝色部分为我的数据库的实例名,因为我用的是EXPRESS版的,所以实例名就那样了,然后红色部分的话是端口,这个端口可不像以前那样的1433了,他有可能是随机的,我们可在「开始」菜单→程序→Microsoft SQL Server 2005→配置工具→SQL Server 配置管理器 中找到,打开后在左栏定位到 SQL Server 2005网络配置→SQLEXPRESS的协议,在右边双击TCP/IP,在弹出的窗口查看IP地址,即可看到动态端口了,或许也可以给他设置一个固定的端口吧,这我没试过,呵呵.

  JDBC驱动程序是从微软官网上下载的,下面是地址:

Microsoft SQL Server 2005 JDBC Driver下载点:http://msdn2.microsoft.com/en-us/data/aa937724.aspx
       Microsoft SQL Server 2005 的JDBC文档为:http://msdn2.microsoft.com/zh-cn/library/ms378956.aspx

  再提醒一下,我下载的驱动程序是sqljdbc_2.0.1008.2_enu.exe,解压出来后里面有2个JAR包,sqljdbc.jar和sqljdbc4.jar两个包,我的JAVA版本是java version "1.6.0_10-rc2",一开始我把两个包都放到WEB-INF下的iib目录中(我是用WEB来做连接测试的,方便!!!),运行的时候出现错误,说是JDK 1.6的版本不支持sqljdbc.jar包里的驱动程序,要用sqljdbc4.jar来代替,我看了一下,sqljdbc.jar和sqljdbc4.jar两个包里的东西都是相同的,可能程序默认调用的是sqljdbc.jar里的吧,随后我把sqljdbc.jar从lib目录中删除掉,再测试的时候就没有问题了,pubs里的数据成功取出!!!

文章参考:http://www.cnblogs.com/mikeye/archive/2007/04/13/711878.html

你可能感兴趣的:(java,sql,sql,exception,server,jdbc,Microsoft)