请大家帮帮忙嘛,怎么利用Microsoft SQL Server 2000 Driver for JDBC连接数据库,我知道要写一定的代码,但是怎么写这些代码了?
我想知道具体的方法,怎么更好的连接SQL数据库?请写清楚具体步骤和写下具体的代码!我在谢谢大家了!谢谢哈!!

解决方案 »

  1.   

    如何开始使用 Microsoft JDBC
    http://support.microsoft.com/kb/313100/zh-cn概要
    设置 CLASSPATH 变量
    注册驱动程序
    传递连接 URL 
    用于测试连接的代码示例
    有关排除连接故障的基本信息概要
    本文介绍如何使用 Microsoft SQL Server 2000 JDBC 驱动程序连接到 SQL Server 2000。注意:有关 Microsoft SQL Server 2000 JDBC 驱动程序的安装说明,请参见 Microsoft SQL Server 2000 Driver for JDBC 安装指南。安装了 Microsoft SQL Server 2000 JDBC 驱动程序后,可以通过两种方式从您的程序连接到数据库:使用连接 URL,或使用 JNDI 数据源。本文介绍如何使用连接 URL 配置和测试数据库连接。 连接到数据库的一种方法是通过 JDBC 驱动程序管理器,使用 DriverManager 类的 getConnection 方法。使用此方法时,最简单的方式是使用一个包含 URL、用户名和密码的字符串参数。本文中的以下几节将介绍如何从 JDBC 程序载入 Microsoft SQL Server 2000 JDBC 驱动程序。
    设置 CLASSPATH 变量
    Microsoft SQL Server 2000 JDBC 驱动程序 .jar 文件必须在 CLASSPATH 变量中列出。CLASSPATH 变量是 Java 虚拟机 (JVM) 用于在您的计算机上查找 JDBC 驱动程序的搜索字符串。如果驱动程序未在 CLASSPATH 变量中列出,尝试载入驱动程序时将出现以下错误信息: 
    java.lang.ClassNotFoundException:com/microsoft/jdbc/sqlserver/SQLServerDriver 
    设置系统 CLASSPATH 变量,加入以下各项: 
    • \Your installation path\Lib\Msbase.jar 
    • \Your installation path\Lib\Msutil.jar 
    • \Your installation path\Lib\Mssqlserver.jar  
    以下是一个配置好的 CLASSPATH 变量的示例: 
    CLASSPATH=.;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msbase.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msutil.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\mssqlserver.jar 
    注册驱动程序
    注册驱动程序的目的是为了通知 JDBC 驱动程序管理器载入哪个驱动程序。当使用 class.forName 函数载入驱动程序时,您必须指定驱动程序的名称。以下是 Microsoft SQL Server 2000 JDBC 驱动程序的名称: 
    com.microsoft.jdbc.sqlserver.SQLServerDriver 
    下面的代码示例演示如何注册驱动程序: Driver d = (Driver)Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
    传递连接 URL 
    必须以连接 URL 的形式传递数据库连接信息。以下是 Microsoft SQL Server 2000 JDBC 驱动程序的模板 URL。请用您数据库的值替换以下值: 
    jdbc:microsoft:sqlserver://servername:1433 
    下面的代码示例演示如何指定连接 URL: con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433", "userName", "password");

    服务器名称值可以是 IP 地址或主机名(假定您的网络可以将主机名解析为 IP 地址)。您可以通过对主机名执行 PING 命令来进行测试,验证是否可以接收到响应,以及响应的 IP 地址是否正确。 服务器名称后面的数字值是数据库侦听的端口号。上文列出的值是示例默认值。确保用您的数据库使用的端口号替换该值。 要获取连接 URL 参数的完整列表,请参见 Microsoft SQL Server 2000 JDBC 驱动程序 HTML 帮助,或参见联机指南。请参见“连接字符串属性”一节。 
    用于测试连接的代码示例
    下面的代码示例尝试连接到数据库,并显示数据库名称、版本和可用编目。请用您服务器的值替换代码中的服务器属性: 
    import java.*;
    public class Connect{
         private java.sql.Connection  con = null;
         private final String url = "jdbc:microsoft:sqlserver://";
         private final String serverName= "localhost";
         private final String portNumber = "1433";
         private final String databaseName= "pubs";
         private final String userName = "user";
         private final String password = "password";
         // Informs the driver to use server a side-cursor, 
         // which permits more than one active statement 
         // on a connection.
         private final String selectMethod = "cursor"; 
         
         // Constructor
         public Connect(){}
         
         private String getConnectionUrl(){
              return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
         }
         
         private java.sql.Connection getConnection(){
              try{
                   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); 
                   con = java.sql.DriverManager.getConnection(getConnectionUrl(),userName,password);
                   if(con!=null) System.out.println("Connection Successful!");
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Error Trace in getConnection() : " + e.getMessage());
             }
              return con;
          }     /*
              Display the driver properties, database details 
         */      public void displayDbProperties(){
              java.sql.DatabaseMetaData dm = null;
              java.sql.ResultSet rs = null;
              try{
                   con= this.getConnection();
                   if(con!=null){
                        dm = con.getMetaData();
                        System.out.println("Driver Information");
                        System.out.println("\tDriver Name: "+ dm.getDriverName());
                        System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
                        System.out.println("\nDatabase Information ");
                        System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
                        System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
                        System.out.println("Avalilable Catalogs ");
                        rs = dm.getCatalogs();
                        while(rs.next()){
                             System.out.println("\tcatalog: "+ rs.getString(1));
                        } 
                        rs.close();
                        rs = null;
                        closeConnection();
                   }else System.out.println("Error: No active Connection");
              }catch(Exception e){
                   e.printStackTrace();
              }
              dm=null;
         }     
         
         private void closeConnection(){
              try{
                   if(con!=null)
                        con.close();
                   con=null;
              }catch(Exception e){
                   e.printStackTrace();
              }
         }
         public static void main(String[] args) throws Exception
           {
              Connect myDbTest = new Connect();
              myDbTest.displayDbProperties();
           }
    }
    如果此代码运行成功,其输出结果应类似于以下内容: 
    Connection Successful!
    Driver Information
    Driver Name:SQLServer
    Driver Version: 2.2.0022Database Information
    Database Name:Microsoft SQL Server
    Database Version:Microsoft SQL Server  2000 - 8.00.384 (Intel X86)
    May 23 2001 00:02:52
    Copyright (c) 1988-2000 Microsoft Corporation
    Desktop Engine on Windows NT 5.1 (Build 2600: )Avalilable Catalogs
    catalog:master
    catalog:msdb
    catalog:pubs
    catalog:tempdb
    有关排除连接故障的基本信息
    下面是尝试连接到 SQL 服务器时常见的错误信息: 
    java.sql.SQLException:[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]Login failed for user 'user'.Reason:Not associated with a trusted SQL Server connection.
    如果将 SQL Server 2000 的验证模式设置为“Windows 验证模式”,则会出现此错误信息。Microsoft SQL Server 2000 JDBC 驱动程序不支持使用 Windows NT 验证进行连接。您必须将 SQL Server 的验证模式设置为“混合模式”,该模式既允许 Windows 验证,也允许 SQL Server 验证。 
    java.sql.SQLException:[Microsoft][SQLServer 2000 Driver for JDBC]This version of the JDBC driver only supports Microsoft SQL Server 2000. You can either upgrade to SQL Server 2000 or possibly locate another version of the driver.
    当您尝试连接到 SQL Server 2000 以前的 SQL Server 版本时,则会出现此错误信息。Microsoft SQL Server 2000 JDBC 驱动程序仅支持与 SQL Server 2000 进行连接。
      

  2.   

    import javax.naming.*;
    import javax.sql.DataSource;public class DataBase {
     private Connection conn=null;
     public DataBase() {
     }
     /*返回数据库连接
       *return @param conn
       * throws SQLException
       */
    public Connection getJDBCConnection()throws SQLException{
            try{
                Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                
                
                    try{                 
                      conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs","sa","");
                 
                    }catch(SQLException se){
                    throw new SQLException("RUL class  not found\n"+se.toString());
                    }
                }catch(ClassNotFoundException ce){
                              throw new SQLException("Driver class  not found\n" + ce.toString());
                           }
     return conn;
    }
    /*关闭ResultSet对象*/
      public static  void closeResultSet(ResultSet rs){
        try{
            if(rs!=null)
              rs.close();
        }catch(SQLException pe){
         System.out.println("ResultSet close ERROR: "+pe.toString());
        }  }
      /*关闭PrepareStatement 对象*/
      public static  void closePreparedStatement(PreparedStatement pstmt) {
           try{
               if(pstmt!=null)
                 pstmt.close();
           }catch(SQLException pe){
            System.out.println("PreparedStatement close ERROR: "+pe.toString());
           }
      }
      /*关闭Statement 对象*/
      public static  void closeStatement(Statement stmt){
        try{
              if(stmt!=null)
                stmt.close();
          }catch(SQLException pe){
           System.out.println("Statement close ERROR: "+pe.toString());
          }
     }
     /*关闭Connection 对象*/
     public static  void closeConnection(Connection conn){
       try{
           if(conn!=null)
             conn.close();
       }catch(SQLException pe){
        System.out.println("Connection close ERROR: "+pe.toString());
       } }
     /**
      *
      * @param conn
      * @param p
      * @param rs
      */
    public static void closeCPR(Connection conn,PreparedStatement  p,ResultSet rs){
       try{
         if (rs != null)
           rs.close();
         if (p != null)
           p.close();
         if (conn != null)
           conn.close();
      }catch(SQLException pe){
        System.out.println("Connection close ERROR: "+pe.toString());
       } }
     public static void closeCSR(Connection conn,Statement  p,ResultSet rs){
       try{
         if(rs!=null)
             rs.close();
           if(p!=null)
             p.close();
           if(conn!=null)
             conn.close();
       }catch(SQLException pe){
        System.out.println("Connection close ERROR: "+pe.toString());
       } }
     public static void main(String[] args)
     {
       DataBase d = new DataBase();
       try
       {
         d.getJDBCConnection();
         ResultSet rs = d.getJDBCConnection().createStatement().executeQuery("select * from jobs");
         while(rs.next())
         {
           System.out.println("_______"+rs.getString(1));
         }
       }catch(Exception ex)
       {
         System.out.println(ex);
       }
     }}
      

  3.   

    还真能复制粘贴//加载驱动,以桥接驱动的方式Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//创建连接,使用NT验证的数据源Connection con = DriverManager.getConnection("jdbc:odbc:test");//创建查询语句Statement s = con.createStatement();//接收结果集ResultSet rs = s.executeQuery(sql);//sql为你要查询的SQL语句rs.close();
    s.close();
    con.close();//分别关闭连接等。
      

  4.   

    JDBC的使用步骤
       import java.sql.*;
       1)加载驱动
       2)得到连接
       3)得到陈述对象
       4)执行操作,得到结果集
       5)操作结果集(循环)
       6)关闭(结果集、陈述对象、连接)import java.sql.*;
    import java.util.*;
    public class JdbcTest{
    public static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
    public static final String URL = "jdbc:oracle:thin:@192.168.0.20:1521:tarena";
     //jdbc:协议:子协议:@host:oracle端口:sid
        public static final String USER = "scott";
    public static final String PASSWORD = "tiger";    public static void main(String[] args) throws ClassNotFoundException,SQLException{
    JdbcTest jt = new JdbcTest();
    //jt.create(2,"hehe","[email protected]");
    //jt.findAll();
    int id = 2;
    Userinfo user = jt.find(id);
    if(user!=null){
    System.out.println(user);
    }else{
    System.out.println("user not found:id="+id);
    }
    //delete by id
    jt.delete(id);
    List users = jt.findAll();
    System.out.println("there are "+users.size()+" users");
    Iterator it = users.iterator();
    String email = "[email protected]";
    Userinfo userFound = null;
    while(it.hasNext()){
    user = (Userinfo)it.next();
    if(user.getEmail().equals(email)){
    userFound = user;
    }
    System.out.println(user);
    }
    System.out.println("-------------");
    if(userFound!=null){
    System.out.println(userFound);
    }
    }
    public static Connection getCon(){
    Connection con = null;
    try{
    Class.forName(ORACLE_DRIVER);
    con = DriverManager.getConnection(URL,USER,PASSWORD);
    }catch(ClassNotFoundException e){
    e.printStackTrace();
    }catch(SQLException e){
    e.printStackTrace();
    }
    return con;
    }
    public Userinfo find(int id){
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    Userinfo user = null;
    try{
    //2、得到连接
    conn = getCon();
    //3、得到陈述对象
    stmt = conn.createStatement();
    String sql = "select * from tb_userinfo where id="+id;

    //4、得到结果集
    rs = stmt.executeQuery(sql);
    //5、操作结果集

    String name;
    String email;
    //System.out.println("id"+"\t"+"name"+"\t"+"email");
    //System.out.println("-----"+"\t"+"-----");
    if(rs.next()){
    id = rs.getInt("id");
    name = rs.getString("name");
    email = rs.getString("email");
    user = new Userinfo(id,name,email);
    //System.out.println(id+"\t"+name+"\t"+email);
    }
    }catch(SQLException e){
    e.printStackTrace();
    }finally{
    //6、关闭
    if(rs!=null){
    try{
    rs.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    if(stmt!=null){
    try{
    stmt.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    if(conn!=null){
    try{
    conn.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    }
    return user;
    }
    public void delete(int id){
    Connection conn = getCon();
    Statement stmt = null;
    try{
    stmt = conn.createStatement();
    String sql = "delete from tb_userinfo"
    +" where id="+id;
    System.out.println("sql:"+sql);
    stmt.executeUpdate(sql);
    }catch(SQLException e){
    e.printStackTrace();
    }finally{
    if(stmt!=null){
    try{
    stmt.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    if(conn!=null){
    try{
    stmt.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    } }
    public void create(int id,String name,String email){
    Connection conn = getCon();
    Statement stmt = null;
    try{
    stmt = conn.createStatement();
    String sql = "insert into tb_userinfo"
    +"(id,name,email)values"
    +"("+id+",'"+name+"','"+email+"')";
    System.out.println("sql:"+sql);
    stmt.executeUpdate(sql);
    }catch(SQLException e){
    e.printStackTrace();
    }finally{
    if(stmt!=null){
    try{
    stmt.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    if(conn!=null){
    try{
    stmt.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    } }
    public List findAll(){
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    List users = new ArrayList();
    try{
    //1、加载驱动
    Class.forName(ORACLE_DRIVER);
    //2、得到连接
    conn = DriverManager.getConnection(URL,USER,PASSWORD);
    //3、得到陈述对象
    stmt = conn.createStatement();
    String sql = "select * from tb_userinfo";

    //4、得到结果集
    rs = stmt.executeQuery(sql);
    //5、操作结果集
    int id;
    String name;
    String email;
    System.out.println("id"+"\t"+"name"+"\t"+"email");
    System.out.println("-----"+"\t"+"-----");
    Userinfo user = null;
    while(rs.next()){
    id = rs.getInt("id");
    name = rs.getString("name");
    email = rs.getString("email");
    user = new Userinfo(id,name,email);
    users.add(user);
    System.out.println(id+"\t"+name+"\t"+email);
    }
    }catch(ClassNotFoundException e){
    //System.out.println("error!");
    e.printStackTrace();
    }catch(SQLException e){
    e.printStackTrace();
    }finally{
    //6、关闭
    if(rs!=null){
    try{
    rs.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    if(stmt!=null){
    try{
    stmt.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    if(conn!=null){
    try{
    conn.close();
    }catch(SQLException e){
    e.printStackTrace();
    }
    }
    }
    return users;    }}
      

  5.   

    顶一个复制粘贴的...orz...
    希望楼主可以看懂1楼及2楼同志的粘贴答案...
    更希望楼主能弄懂连接SQL的过程...
    我觉得就大致四步:
    1.连接数据库:Connection con = DriverManager.getConnection(你要连接的数据库所在)..当然之前要
    Class.forName(你的连接驱动) 
    2.建立statement或PreparedStatement对象(向数据库发送请求)
    3.建立ResultSet对象(回收数据库结果集).
    4.关闭数据库连接close()...
    具体的代码希望楼主能从1楼及2楼答案找到想要的答案...
    祝福楼主...