---
title: "jdbc连接SQL server2000"
author: "wandering192"
date: "2010-10-22T13:16:32Z"
tags: []
categories: ["数据库"]
slug: "jdbc-sql-server2000"
draft: false
lastmod: "2010-10-22T13:16:32Z"
id: 791410
url: "https://wandering192.iteye.com/blog/791410"
---

1.假设SQL数据库“test”下有表“PRESON”

 

![](http://dl.iteye.com/upload/attachment/335599/7cd64d56-fe95-3b17-9cce-91bb0017e310.png)

 

2.连接表PERSON并打印出表的每一行：

 

```
package com.myjava;

import java.sql.SQLException;

public class TestJDBCSQL {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		java.sql.Connection con = null;
		java.sql.Statement stmt = null;
		java.sql.ResultSet rs = null;
		String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test";
		String q = "select * from PERSON";
		
		try {
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try{
			con = java.sql.DriverManager.getConnection(url, "sa", "");
			stmt = con.createStatement();
			rs = stmt.executeQuery(q);
			while(rs.next()) {
				String name = rs.getString(1);
				java.sql.Date time = rs.getDate(2);
				String content = rs.getString(3);
				int id = rs.getInt(4);
				System.out.println(name + "\t" + time + "\t" + content + "\t" + id);
			}
			
		}catch (java.sql.SQLException sqe){
			sqe.printStackTrace();
		}
		
		try {
			rs.close();
			stmt.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

}
```

 

 3.说明及调试：要注意15行中url的准确性，同时注意26行取得数据库连接时用的用户名以及密码是否与数据库的用户名和登录密码相匹配。

 

4.在初步测试时，由于将15行中的localhost:1433错写成localhost:1443，结果出现如下错误：

```
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Error establishing socket.
	at com.microsoft.jdbc.base.BaseExceptions.createException(Unknown Source)
	at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
	at com.microsoft.jdbc.base.BaseExceptions.getException(Unknown Source)
	at com.microsoft.jdbc.sqlserver.tds.TDSConnection.<init>(Unknown Source)
	at com.microsoft.jdbc.sqlserver.SQLServerImplConnection.open(Unknown Source)
	at com.microsoft.jdbc.base.BaseConnection.getNewImplConnection(Unknown Source)
	at com.microsoft.jdbc.base.BaseConnection.open(Unknown Source)
	at com.microsoft.jdbc.base.BaseDriver.connect(Unknown Source)
	at java.sql.DriverManager.getConnection(DriverManager.java:582)
	at java.sql.DriverManager.getConnection(DriverManager.java:185)
	at com.myjava.TestJDBCSQL.main(TestJDBCSQL.java:26)
Exception in thread "main" java.lang.NullPointerException
	at com.myjava.TestJDBCSQL.main(TestJDBCSQL.java:42)
```

 5.使用netstat查看使用端口

```
netstat -a -n
```

 6.或者直接查询端口

```
netstat -a -n |find "1443"
```

 发现端口1443没有处于服务状态，而仔细查看SQL端口后，知道SQL端口应该是“1433”，果断改代码，连接成功。