代码如下:
package com.jrc.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
/**
* @param args
* @throws SQLException
*/
//public final static String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
//public final static String URL="jdbc:sqlserver://127.1:1433;DatabaseName=MySchool";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
Connection conn=null;
Statement st=null;
ResultSet rs=null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=StudentS");
st = conn.createStatement();
System.out.println("连接成功");
rs = st.executeQuery("select*from dbo.Table_1");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t");
System.out.println(rs.getInt(2)+"\t");
System.out.println(rs.getString(3)+"\t");
}
rs.close();
st.close();
conn.close();
}
}
运行时出现这样的错误:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: 到主机 的 TCP/IP 连接失败。 java.net.ConnectException: Connection refused: connect
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.loginWithoutFailover(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(Unknown Source)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at com.jrc.jdbc.JdbcTest.main(JdbcTest.java:27)
sql server的TCP服务我也开了,就是不知道问题错在哪???
我那个驱动包名是:sqljdbc.jar
电脑运行系统是:Win7
------解决方案--------------------
user=MyUserName;password=*****加这两个属性
------解决方案--------------------
为了更好的给LZ解释清楚,我自己动手安装了SQLServer2005 ,还好有自己还有64bit版的。结果不会影响。(因为我自己的电脑是64bit)
关于JDBC连接的代码我就不封装了,完全按照LZ的代码来。
如下:
package sqlserver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTest {
public static void main(String []args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//注册驱动