JDBC:简单的 MSSql 连接示例不起作用 [英] JDBC: Simple MSSql connection example not working

查看:25
本文介绍了JDBC:简单的 MSSql 连接示例不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Java,只需运行一些简单的程序即可通过 JDBC 从 MSSQL 检索一些数据.我书中的例子不起作用(但它已经有好几年了),下面这个来自 MS 的例子对我也不起作用:

I am learning Java and need to just run something simple to retrieve some data from MSSQL via JDBC. The example in my book doesn't work (but it is several years old) and this example below from MS doesn't work for me either:

http://msdn.microsoft.com/en-us/library/ms378956(v=sql.90).aspx

这是我的代码:

package javasql;
import java.sql.*;
import java.util.*;

public class Program {

    private static String url = "jdbc:sqlserver://localhost\SQLExpress;database=Northwind;integratedSecurity=true;";
    //private static String userName = "sa";
    //private static String password = "myPassword";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        RunDemo();
    }

    public static void RunDemo() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Connection connection = DriverManager.getConnection(url);

            Statement statement = connection.createStatement();
            ResultSet results = statement.executeQuery("SELECT ProductName, Price FROM Products ORDER BY ProductName");

            while(results.next()) {
                System.out.println("Product Name: " + results.getNString("ProductName") + " Price: $" + results.getFloat("UnitPrice"));
            }

        } catch (ClassNotFoundException | SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

当我运行代码时,我没有抛出任何异常..我只是在输出窗口中得到这个:

When I run the code, I don't get any exceptions thrown.. I just get this in the output window:

run:
com.microsoft.sqlserver.jdbc.SQLServerDriver
BUILD SUCCESSFUL (total time: 0 seconds)

我使用的是 NetBeans 7.2.请有人给我一个可行的例子.

I am using NetBeans 7.2. Please someone give me a working example.

顺便说一下,对于连接字符串,您可以在其中看到 \SQLExpress,我确实尝试删除它并使用 instanceName=SQLExpress 代替.. 但这并没有也没有任何影响.

By the way, for the connection string, where you see the \SQLExpress, I did try removing that and using instanceName=SQLExpress instead.. but that didn't have any effect either.

编辑 2:

好的,我从 MS 下载了最新的 MSSQL JDBC 驱动程序,并引用了其中的 2 个 JAR 文件.现在我得到这个输出:

OK, I downloaded the latest JDBC driver for MSSQL from MS and referenced the 2 JAR files in there. Now I'm getting this output:

run:
The connection to the host localhost, named instance SQLExpress failed. 

Error: "java.net.SocketTimeoutException: Receive timed out". 

Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434.  
For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
BUILD SUCCESSFUL (total time: 15 seconds)

进展..至少我们现在可以看到它正在尝试连接,有人能告诉我上述错误吗?

Progress.. at least we can see it is trying to connect now, can someone enlighten me as to the above error though?

编辑 3:

修复了另外两个问题.一个是启用 SQL Server 浏览器,第二个是启用 SQL Server 的 TCP/IP.谢谢@Vikdor 现在我收到此错误:

2 more problems fixed.. one is enable SQL Server Browser and the second was enabling TCP/IP for SQL Server. Thanks @Vikdor Now I'm getting this error:

run:
The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
BUILD SUCCESSFUL (total time: 15 seconds)

我检查了 Windows 防火墙并添加了一个入站规则以允许该端口,但我仍然收到上述错误.有什么想法吗?

I checked windows firewall and added an inbound rule to allow that port, but I'm still getting the above error. Any ideas?

编辑 4:

在此链接中尝试了解决方案:http://www.coderanch.com/t/306316/JDBC/databases/SQLServerException-TCP-IP-connection-host

Tried the solution in this link: http://www.coderanch.com/t/306316/JDBC/databases/SQLServerException-TCP-IP-connection-host

在 EDIT 3 中不再出现错误.现在得到另一个......

No longer getting error in EDIT 3. Now getting another...

run:
Sep 21, 2012 11:33:16 AM com.microsoft.sqlserver.jdbc.AuthenticationJNI <clinit>
WARNING: Failed to load the sqljdbc_auth.dll cause : no sqljdbc_auth in java.library.path
This driver is not configured for integrated authentication. ClientConnectionId:577f359e-4774-45f3-96fb-588785911817
BUILD SUCCESSFUL (total time: 14 seconds)

现在对此感到非常厌倦..为什么是 Java,为什么?说真的...我很高兴我主要使用 .NET.好吧,当我找到解决方案时,我会将其发布在这里以确保它可以帮助其他人,以免他们发疯,因为我即将...

Getting very tired of this now.. why Java, why?? Seriously...I'm glad I work mostly with .NET. Well, when i find the solution, I will post it here to make sure it can help others before they go mad as I am about to...

编辑 5:

这有助于:java 连接到 MicrosoftSQLServer 2005

我将目录路径放入我的 PATH 环境变量中.没有用,所以我也把 sqljdbc_auth.dll 放到了我的 JDK 文件夹 C:Program FilesJavajdk1.7.0_04in 中.解决了.​​

I put the directory path into my PATH environment variable. Didn't work, so I also placed the sqljdbc_auth.dll into my JDK folder C:Program FilesJavajdk1.7.0_04in. Solved.

推荐答案

好的,以下是解决我问题的方法:

OK, so here's what solved my problems:

  1. 从这里下载最新的 MSSQL JDBC 驱动程序:http://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx

在我的项目中引用了 2 个 JAR 文件:sqljdbc.jarsqljdbc4.jar(我还不确定是需要以上两个还是只有一个..)

Referenced the 2 JAR files in my project: sqljdbc.jar and sqljdbc4.jar (I'm not yet sure if both of the above are required or just one..)

确保 SQL Server Browser windows 服务正在运行

Make sure the SQL Server Browser windows service is running

打开 SQL Server 配置管理器并转到 SQL Server 网络配置下的SQLEXPRESS 协议.右键单击 TCP/IP 并选择属性.设置启用 = YES.

Open SQL Server Configuration Manager and go to Protocols for SQLEXPRESS under SQL Server Network Configuration. Right-click on TCP/IP and choose Properties. Set Enabled = YES.

当您在那里时,点击IP 地址 标签并找到IP 全部 部分.将 TCP 端口 设置为 1433.

While you're there, click on IP Addresses tab and find the section IP All. Set TCP Port to 1433.

sqljdbc_auth.dll 添加到您的 PATH 环境变量.就我而言:D:Javasqljdbc_4.0enuauthx64

Add sqljdbc_auth.dll to your PATH Environment Variable. In my case: D:Javasqljdbc_4.0enuauthx64

sqljdbc_auth.dll 复制到您的 JDK 目录.就我而言:C:Program FilesJavajdk1.7.0_04in

Copy the sqljdbc_auth.dll to your JDK directory. In my case: C:Program FilesJavajdk1.7.0_04in

我希望这对某人有所帮助.

I hope this helps someone.

这篇关于JDBC:简单的 MSSql 连接示例不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆