孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

       用JDBC连接SQL SERVER2000,需要SQL SERVER2000装上SP4补丁,并且下载Microsoft SQL Server for JDBC的驱动,下载后解压,会有两个JAR文件,分别为sqljdbc4.jar和sqljdbc.jar文件,目前JAVA版本都使用sqljdbc4.jar,将这两个文件拷贝至D:\Program Files\NetBeans 7.0.1\jdbc\SQLServerJDBC\lib

(首先必须创建这个目录),在NetBeans的菜单工具->库中新建SqlserverJDBC库,并选择sqljdbc4.jar文件。

       新建一工程,假设为TestDB,在工程属性的库中添加SqlserverJDBC库,然后编写代码:

   /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testdb;

import java.sql.*;

/**
 *
 * @author dongjichao
 */
public class TestDB {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

      // Create a variable for the connection string.
      String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
            "databaseName=Northwind;";

      // 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,"sa","");

         // Create and execute an SQL statement that returns a
         // set of data and then display it.
         String SQL = "SELECT * FROM Products;";
         stmt = con.createStatement();
         rs = stmt.executeQuery(SQL);
         displayRow("PRODUCTS", rs);
      }

      // 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) {}
      }
   }

   private static void displayRow(String title, ResultSet rs) {
      try {
         System.out.println(title);
         while (rs.next()) {
            System.out.println(rs.getString("ProductName") + " : " + rs.getString("ProductID"));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

运行程序即可看到从数据库中取得的数据

posted on 2011-09-22 20:11  孤独的猫  阅读(591)  评论(0)    收藏  举报