据说微软提供的jdbc驱动不支持"反复查询",所以用net.sourceforge.jtds.jdbc.Driver(http://jtds.sourceforge.net/)
在Win2003Server上安装SQLSERVER2000,必须安装补丁sp3
写类时注意:JAVA中CLASS.FORNAME方法必须是一个可以捕获的错误,把它放在TRY{}CATCH(CLASSNOTFOUNTEXCEPTION){}中就不会出错了
另CLASS_PATH中必须加入jtds-x-x-x.jar的完整路径名如:.\;...;D:\j2sdk1.4.2_01\jre\lib\ext\jtds-0.5.1.jar;
/*
* Author:liufei
* Homepage: http://www.liufei.com
* Copyright 2003 henan SUNCER software Inc. All rights reserved.
*/
import java.sql.*;
import java.util.*;
class Sql {
public static void main(String[] args) {
try{
String query="select * from Orders";
String URL="jdbc:jtds:sqlserver://135.0.0.2:1433/Northwind;USER=sa;PASSWORD=webserver";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn=DriverManager.getConnection(URL);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery(query);
int i=0;
for(i=0;i<10;i++){
rs.next();
System.out.println(rs.getString(1));
}
//SQLServer2K自带的样例数据库Northwind中,表Orders有多于10条,可能上百条记录,所以只列10条!
}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.*"%>
<html>
<body>
<%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();
%>
</body>
</html>
本文地址:http://com.8s8s.com/it/it16973.htm