JDBC下,SQLServer 2005的配置,与实例代码

来源:互联网 发布:如何关闭mac自启动程序 编辑:程序博客网 时间:2024/05/13 11:16

配置

1、下载并关联所需的 驱动包

①下载地址:http://download.csdn.net/detail/justoneroad/4032878
②关联:这驱动包是一个jar包,我们可以在CLASSPATH路径下关联它

2、配置SQLServer 2005 的TCP/IP连接选项

①找到SQL Server 2005 的 配置管理器。(所有程序-->SQLServer2005-->配置工具-->SQLServer2005配置管理器)

②找到TCP/IP选项。(SQLServer2005 网络配置-->SQLEXPRESS协议-->TCP/IP)

③配置TCP/IP
首先,右击“TCP/IP"将其启用;
然后,双击”TCP/IP"-->IP 地址 --> IP All --> TCP端口设为1433

④保存这些配置,重启数据库

实例代码

/**   * @Title: use_preparedStatement.java* @Package jdbc* @Description: 在jdbc的方式下,用preparedStatement方式执行一条查询语句* @author 慢跑学Android* @date 2012-1-27 下午03:04:09* @version V1.0   */package jdbc;import java.sql.*;public class use_preparedStatement {public static void main(String[] args) {Connection connection = null;PreparedStatement preparedStatement = null;ResultSet resultSet = null;try {/** * Connect to the target SQL Server. */// ①2005的驱动路径和2000不一样②连接路径也不一样Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Company","sa","sasa");/** * Execute a SQL statement with PreparedStatement. */String sql = "select 员工Id,姓名,部门编号 from employee where 部门编号=?";preparedStatement = connection.prepareStatement(sql);preparedStatement.setInt(1, 20);resultSet = preparedStatement.executeQuery();System.out.println("员工Id\t" + "姓名\t" + "部门编号\n");while (resultSet.next()) {System.out.println(resultSet.getInt("员工Id") + "\t"+ resultSet.getString(2) + "\t"+ resultSet.getInt(3));}} catch (Exception e) {e.printStackTrace();} finally {/** * Release the resource. */try {if (null != resultSet) {resultSet.close();}if (null != preparedStatement) {preparedStatement.close();}if (null != connection) {connection.close();}} catch (Exception e) {e.printStackTrace();}}}}

运行结果图: