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

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

问题描述

我正在学习Java,需要运行一些简单的东西,通过JDBC从MSSQL中检索一些数据。我书中的例子不起作用(但它已经有好几年了)以下MS的这个例子对我来说也不起作用:



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



这是我的代码:

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

公共类程序{

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

/ **
* @param args命令行参数
* /
public static void main(String [] args){
RunDemo( );
}

public static void RunDemo(){
try {
Class.forName(com.microsoft.sqlserver.jdbc.SQLServerDriver);
连接连接= 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(产品名称:+ results.getNString(ProductName)+Price:$+结果。 getFloat( 单价));
}

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

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

 运行:
com .microsoft.sqlserver.jdbc.SQLServerDriver
BUILD SUCCESSFUL(总时间:0秒)

我正在使用NetBeans 7.2。请有人给我一个有效的例子。



编辑:



顺便说一下,对于连接字符串,您看到 \\SQLExpress ,我确实尝试删除它并使用 instanceName = SQLExpress 相反..但也没有任何影响。



编辑2:



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

 运行:
与主机localhost的连接,命名实例SQLExpress失败。

错误:java.net.SocketTimeoutException:Receive timed out。

验证服务器和实例名称,并检查没有防火墙阻止到端口1434的UDP流量。
对于SQL Server 2005或更高版本,请验证SQL Server Browser服务是否在主机上运行。
BUILD SUCCESSFUL(总时间:15秒)

进展..至少我们可以看到它现在试图连接,有人可以告诉我上面的错误吗?



编辑3:



修复了2个问题..一个是启用SQL Server Browser,另一个是启用SQL Server的TCP / IP。谢谢@Vikdor现在我收到此错误:

 运行:
与主机localhost的TCP / IP连接,端口1433失败了。错误:连接被拒绝:连接。验证连接属性。确保在主机上运行SQL Server实例并接受端口上的TCP / IP连接。确保防火墙不阻止与端口的TCP连接。
BUILD SUCCESSFUL(总时间:15秒)

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



编辑4:



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



在编辑中不再出错3.现在获取另一个......

 运行:
2012年9月21日上午11:33:16 com.microsoft.sqlserver。 jdbc.AuthenticationJNI< clinit>
警告:无法加载sqljdbc_auth.dll原因:java.library.path中没有sqljdbc_auth
此驱动程序未配置为集成身份验证。 ClientConnectionId:577f359e-4774-45f3-96fb-588785911817
BUILD SUCCESSFUL(总时间:14秒)

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



编辑5:



这有助于:
java连接到MicrosoftSQLServer 2005



我将目录路径放入我的PATH环境变量中。没用,所以我也将 sqljdbc_auth.dll 放入我的JDK文件夹 C:\Program Files \ Java \\\\\\\\\\\\\\\\\\ _04\bin 。解决了。​​

解决方案

好的,所以这就解决了我的问题:


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


  2. 引用了2个JAR文件在我的项目中:
    sqljdbc.jar
    sqljdbc4.jar (我还不确定上述两者是否都是必需的或只是一个..)


  3. 确保SQL Server Browser Windows服务正在运行


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


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


  6. sqljdbc_auth.dll 添加到 PATH环境变量即可。就我而言: D:\ Java \sqljdbc_4.0 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ sqljdbc_auth.dll JDK目录。在我的情况下: C:\Program Files\Java\jdk1.7.0_04\bin


我希望这有助于某人。


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

Here's my code:

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)

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

EDIT:

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.

EDIT 2:

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?

EDIT 3:

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)

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

EDIT 4:

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

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)

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...

EDIT 5:

This helped: java connecting to MicrosoftSQLServer 2005

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 Files\Java\jdk1.7.0_04\bin. Solved.

解决方案

OK, so here's what solved my problems:

  1. Download latest MSSQL JDBC driver from here: http://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx

  2. 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..)

  3. Make sure the SQL Server Browser windows service is running

  4. 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.

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

  6. Add sqljdbc_auth.dll to your PATH Environment Variable. In my case: D:\Java\sqljdbc_4.0\enu\auth\x64

  7. Copy the sqljdbc_auth.dll to your JDK directory. In my case: C:\Program Files\Java\jdk1.7.0_04\bin

I hope this helps someone.

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

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