熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java與sqlserver2000的連接

2013-11-23 19:13:44  來源: Java核心技術 

   qiek(原作)
   
  
  據說微軟提供的jdbc驅動不支持反復查詢所以用netsourceforgejtdsjdbcDriver()
  在WinServer上安裝SQLSERVER必須安裝補丁sp
  
  寫類時注意JAVA中CLASSFORNAME方法必須是一個可以捕獲的錯誤把它放在TRY{}CATCH(CLASSNOTFOUNTEXCEPTION){}中就不會出錯了
  另CLASS_PATH中必須加入jtdsxxxjar的完整路徑名如\;;D:\jsdk_\jre\lib\ext\jtdsjar;
  
  /*
   * Author:liufei
   * Homepage:
   * Copyright henan SUNCER software Inc All rights reserved
   */
  import javasql*;
  import javautil*;
  class Sql {
   public static void main(String[] args) {
   try{
     String query=select * from Orders;
    String URL=jdbc:jtds:sqlserver://:/Northwind;USER=sa;PASSWORD=webserver;
    ClassforName(netsourceforgejtdsjdbcDriver);
    Connection conn=DriverManagergetConnection(URL);
    Statement stmt=conncreateStatement(ResultSetTYPE_SCROLL_SENSITIVEResultSetCONCUR_UPDATABLE);
    ResultSet rs=stmtexecuteQuery(query);
   
    int i=;
    for(i=;i <10;i++){
     rs.next();
     System.out.println(rs.getString(1));
    
    }
    }catch(Exception e){
     System.out.println(e.getMessage());
    }
   }
  }
  
  
  用JSP連接:
  
  必須將jtds.jar放至WEB-INF/lib目錄下
  
  test.jsp內容如下:
  
   <%@ page contentType="text/html;charset=gb2312"%>
   <%@ page import="java.sql.*"%>
  
  
   <%Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
  String url="jdbc:jtds:sqlserver://135.0.0.2:1433/Northwind;USER=sa;PASSWORD=webserver";
  
  Connection conn= DriverManager.getConnection(url);
  Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
  String sql="select * from Orders";
  ResultSet rs=stmt.executeQuery(sql);
  while(rs.next()) {%>
  您的第一個字段內容為: <%=rs.getString(1)%>
  您的第二個字段內容為: <%=rs.getString(2)%>
   <%}%>
   <%out.print("數據庫操作成功,恭喜你");%>
   <%rs.close();
  stmt.close();
  conn.close();
  %>
  
  
  

From:http://tw.wingwit.com/Article/program/Java/hx/201311/26483.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.