一、下载安装
1、SQL Server 2005 Express Edition
下载:http://msdn.microsoft.com/vstudio/express/sql/download/
安装完数据库后设置ICP/IP协议启动,具体如下:
(1)打开SQL Server Configuration Manager
(2)转到SQL Server 2005 Network Configuration->Protocols for SQLEXPRESS
(3)将TCP/IP设置为Enabled(启用)
(4)双击TCP/IP项,转到IP Addresses页
(5)IP All中设置TCP Port为1433
(6)重新启动服务
2、SQL Server2005数据库JSP JDBC驱动
下载:http://download.microsoft.com/download/1/c/a/1cae7cc0-c010-4e0c-b1b8-7915360ee0b9/sqljdbc_1.0.809.102_chs.exe
安装或者解压,取得sqljdbc.jar文件,该文件即为JDBC驱动。将sqljdbc.jar放到classpath。(web application中放在WEB-INF/lib下)
二、连接数据库SQL Server2005的Java代码
1、在tempdb中创建测试数据表格
- use tempdb
- CREATE TABLE dbo.Table_1
- (
- ID bigint NOT NULL,
- NAME varchar(20) NOT NULL,
- EMAIL varchar(50) NULL
- ) ON [PRIMARY]
2、测试使用数据库连接
下面代码创建了一个连接到数据库的连接,及使用连接操作数据库。
- package cn.afss.common.web.test;
-
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
-
- import org.apache.log4j.Logger;
-
-
- public class TestConnSql2k5Bean {
-
- private static final Logger logger =
- Logger.getLogger(TestConnSql2k5Bean.class);
- private Connection conn = null;
-
- public TestConnSql2k5Bean() {
- super();
- }
-
- public void getConnection() {
- try {
- Class
- .forName("com.microsoft.SQL Server.jdbc.SQL ServerDriver")
- .newInstance();
- String URL = "jdbc:SQL Server://localhost:1433;DatabaseName=tempdb";
- String USER = "sa";
- String PASSWORD = "123456";
- conn = DriverManager.getConnection(URL, USER, PASSWORD);
- } catch (java.lang.ClassNotFoundException ce) {
- logger.error("Get Connection error:", ce);
- } catch (java.sql.SQLException se) {
- logger.error("Get Connection error:", se);
- } catch (Exception e) {
- logger.error("Get Connection error:", e);
- }
- }
-
- public void testConnection() {
- if (conn == null)
- this.getConnection();
- try {
- String sql = "SELECT * FROM TABLE_1";
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery(sql);
- while (rs.next()) {
- logger.debug(rs.getString("ID"));
- logger.debug(rs.getString("NAME"));
- logger.debug(rs.getString("EMAIL"));
- }
- rs.close();
- stmt.close();
- } catch (SQLException e) {
- logger.error(e.getMessage(), e);
- } finally {
- if (conn != null)
- try {
- conn.close();
- } catch (SQLException e) {
- }
- }
- }
- public static void main(String[] args) {
- TestConnSql2k5Bean bean = new TestConnSql2k5Bean();
- bean.testConnection();
- }
- }
三、SQL Server2000和2005的连接代码区别
写连接代码时需要注意2000和2005的不同:
1、JSP JDBC连接SQL Server2000
- Class.forName("com.microsoft.jdbc.SQL Server.SQL ServerDriver").newInstance();
- URL = "jdbc:microsoft:SQL Server://localhost:1433;DatabaseName=tempdb";
2、JSP JDBC连接SQL Server2005
- Class.forName("com.microsoft.SQL Server.jdbc.SQL ServerDriver").newInstance();
- URL = "jdbc:SQL Server://localhost:1433;DatabaseName=tempdb";