Я пытаюсь подключиться к базе данных SQL Server на моей локальной машине, используя следующий код:
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
import java.sql.*;
public class JDBConn {
//public class connectURL {
public static void main(String[] args) {
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
// Create a variable for the connection string.
//String connectionUrl = "jdbc:sqlserver://localhost;database=optRes1;integratedSecurity=true;";
//con = DriverManager.getConnection(connectionUrl);
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost";
con = DriverManager.getConnection(connectionUrl);
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT * FROM some_table_name");
while (r.next()) {
System.out.println(r.getString(1));
}
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * from [optRes1].[dbo].[unEmpDat]";
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) {}
}
}
}
При попытке подключиться появляется следующее сообщение (я использую Eclipse в качестве IDE):
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
До сих пор я заходил в Mgr Configuration, активировал и включал TCP / IP.
Я также вошел и включил и активировал каждый IP-адрес на вкладке Свойства> IP-адреса.
Пара потенциальных проблем.
Когда я смотрю на состояние браузера SQL Server, он «остановлен». Я не уверен, если это проблема, и если так, как это исправить.
Я использую файл sqljdbc4.jar
, и он находится в разделе «Ссылки на библиотеки» проекта.
Дайте мне знать, если у вас есть предложения, пожалуйста.
EDIT:
Я использую коробку Windows 7.
UPDATE:
>java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) 64-Bit Server VM (build 14.0-b16, mixed mode)