日期:2014-05-18  浏览次数:20774 次

jsp连接sql server 问题
tomcat和sql   server   安装完毕   ,   想用jsp访问sql   server数据库,怎么办?

------解决方案--------------------
<%@ 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为你的数据库的
String user= "sa "; //用户名
String password= " "; //密码
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql= "select * from test ";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next()) out.print( "数据库操作成功,恭喜你 ");
rs.close();
stmt.close();
conn.close();
%>
</body>
------解决方案--------------------
test为你的数据库的PUBS下一张表(里面有内容的)
------解决方案--------------------
封装好的,


package bean;
import java.sql.*;
public class dbcon
{
String user= "sa ";
String password= "sa ";
String driverName= "sun.jdbc.odbc.JdbcOdbcDriver ";
String connectURL= "jdbc:odbc:jspbook ";
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;

public dbcon()
{

try{
Class.forName(driverName);
conn=DriverManager.getConnection(connectURL,user,password);
conn.setAutoCommit(true);
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);


}
catch(Exception e)
{
System.out.println( "数据库连接错误 "+e.getMessage());
}
}
public ResultSet executeQuery(String sql)
{
try{
rs=stmt.executeQuery(sql);
}
catch(SQLException ex)
{
System.out.println( "数据库查询错误 "+ex.getMessage());
}
return rs;
}
public int executeUpdate(String sql)
{
try{
int i=stmt.executeUpdate(sql);
return i;
}
catch(SQLException ex)
{
System.out.println( "执行更新错误: "+ex.getMessage());
return -1;
}
}
public Connection getcon()
{
return conn;
}
}