读书人

java联接SQL Server 2005数据库

发布时间: 2012-08-13 13:21:53 作者: rapoo

java连接SQL Server 2005数据库
1.从微软的网站Microsoft Download Center中上下载所需要用到的jar包 http://download.microsoft.com/download/2/8/9/289dd6a3-eeeb-46dc-9045-d0c6b59bfbc1/sqljdbc_1.1.1501.101_chs.exe

下载并运行此文件后生成的文件夹里面有一个 sqljdbc.jar,用的就是这个jar包。

2.一个连接数据库的java类

import java.sql.*;public class connectURL {public static void main(String[] args) {// Create a variable for the connection string.String connectionUrl = "jdbc:sqlserver://localhost:1433;" +"databaseName=db_search;user=fly;password=jordan123456";// Declare the JDBC objects.Connection con = null;Statement stmt = null;ResultSet rs = null;        try {        // Establish the connection.        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");            con = DriverManager.getConnection(connectionUrl);                        // Create and execute an SQL statement that returns some data.            String SQL = "SELECT TOP 10 * FROM Person.Contact";            stmt = con.createStatement();            rs = stmt.executeQuery(SQL);                        // Iterate through the data in the result set and display it.            while (rs.next()) {            System.out.println(rs.getString(4) + " " + rs.getString(6));            }        }        // Handle any errors that may have occurred.catch (Exception e) {e.printStackTrace();}finally {if (rs != null) try { rs.close(); } catch(Exception e) {}    if (stmt != null) try { stmt.close(); } catch(Exception e) {}    if (con != null) try { con.close(); } catch(Exception e) {}}}}

以上java类摘自微软的官方文档,自己改动了connectionUrl的值

3.启动SQL Server的TCP/IP协议

从开始菜单栏进入到Microsoft SQL Server 2005 --->配置工具--->SQL Server Configuration Manager




4.其它的说明:SQL Server2005SQL Server2000的dirver和url字符串是不一样的。
SQL Server2000
drivername是 com.microsoft.jdbc.sqlserver.SQLServerDriver
url是 jdbc:sqlserver://127.0.0.1:1433;databasename=database1

读书人网 >其他数据库

热点推荐