Проблемы с подключением к Java / SQL Server 2008 R2 Express - PullRequest
0 голосов
/ 26 января 2012

Я пытаюсь подключиться к базе данных 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)

1 Ответ

1 голос
/ 26 января 2012

Вы не указали, какую версию JRE вы используете, но существует известная проблема между 1.6.0_29 и SQL Server 2008, описанная в Идентификатор ошибки 7105007 Также есть поток на форумах Microsoft, где предлагается понижение до 1.6.0_27.

Вы также можете просто заменить _29's jsse.jar на то, что с _27.Это в основном полезно для клиентов Mac OS, где сложно понизить версию.Целевой файл Mac HD -> System -> Library -> Java -> JavaVirtualMachines -> 1.6.0.jdk -> Contents -> Classes -> jsse.jar

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...