jdbc连接数据库
jdbc连接数据库要通过jdbc的驱动,可在微软的官方网站上下到(Microsoft SQL Server 2000 Driver for JDBC)
其次sql2k的服务器一定要打sp3的补丁,否则jdbc访问的1433端口则不能被访问
其次为driver配置环境变量,比如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\mssqlserver.jar;C:\Program Files\Microsoft SQL Server 2000 Driver for JDBC\lib\msutil.jar 这个要根据你的驱动的安装位置
现面给出一个例子:
1 jsp文件
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; //pubs为你的数据库的
Connection conn= DriverManager.getConnection(url,"sa","danlian");
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from authors"; ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%> <%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();%>
</body>
</html>
2 java测试文件
import java.sql.*;
public class Jdbc
{
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String url ="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Northwind";
//String url ="
Connection con;
Statement stmt;
ResultSet rs;
public void connection()
{
try{
Class.forName(driver);
con = DriverManager.getConnection(url,"sa","danlian");
stmt = con.createStatement();
rs = stmt.executeQuery("Select * from Customers");
while(rs.next())
{
System.out.println(rs.getString("CustomerID"));
}
}catch(SQLException ex){ex.printStackTrace();
}
catch(ClassNotFoundException ef)
{
ef.printStackTrace();
}
}
public static void main(String[] args)
{
Jdbc j = new Jdbc();
j.connection();
}
以上再jdk1.5,tomcat5.0,sql2k下通过
回复Comments
{commenttime}{commentauthor}
{CommentUrl}
{commentcontent}