求jsp连接SQL SERVER 2005代码
要求正确的,除了要有正确的代码还要设置什么才能成功连接??
求jsp连接SQL SERVER 2005代码
要求正确的,除了要有正确的代码还要设置什么才能成功连接??
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectionManager {
private static String Driver_Class = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //驱动类连接字符串
private static String Database_Url ="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=数据库名称"; //url
private static String Database_User = "sa"; //数据库用户名
private static String Database_password = "sa"; //密码
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(Driver_Class);
connection = DriverManager.getConnection(Database_Url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void closeAll(ResultSet rs, PreparedStatement pStatement, Connection connection){
try {
if(rs!=null){
rs.close();
rs = null;
}
if(pStatement!=null){
pStatement.close();
pStatement = null;
}
if(connection!=null){
connection.close();
connection = null;
}
}catch (SQLException e) {
e.printStackTrace();
}
}
}
链接sqlserver 需要启动sqlserver 服务 mcrosoft sqlserver 2005-->配置工具-->
sql server configuration manager -->sql server 网络配置-->MSSQLSERVER-->TCP/IP
将协议中已起用改为是 TCP 端口输入1433 已起用改为是
程序中右击 选择属性(properties-->java build path 选择 librares 选择 add external jars...
选中驱动包然后确定就行了
用MyEclipse设置如下:
1、先把SQL2005的连接驱动jar包拷到web的的lib下(jar是2005的不仅可以连2000还可以连2005)
2、
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet;
import com.microsoft.sqlserver.jdbc.SQLServerDriver;
public class DBConn { private static Connection conn=null; private DBConn(){} public static Connection getConnection()throws Exception{ if(conn==null||conn.isClosed()){ new SQLServerDriver(); conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=test","sa","sa"); } return conn; } public static void closeConnection()throws Exception{ if(conn!=null||!conn.isClosed()){ conn.close(); } } public static PreparedStatement getPreparedStatement(String sql)throws Exception{ getConnection(); PreparedStatement pst=conn.prepareStatement(sql); return pst; } public static ResultSet getResultSet(String sql)throws Exception{ ResultSet rst=getPreparedStatement(sql).executeQuery(); return rst; } public static void main(String[] args)throws Exception { DBConn conn=new DBConn(); System.out.println(conn.getConnection()); } }
可以把这个封装成一个jar包以后作为底层的通用都可以!呵呵...
把驱动包加到工作空间里,然后在类里import 相应的类就行了
加SQL SERVER 2005 驱动包