如何使用JDBC连接到SQL Server 2008数据库?

如何使用JDBC连接到SQL Server 2008数据库?

问题描述:

我在本地PC上安装了MSSQL 2008,我的Java应用程序需要连接到MSSQL数据库。我是MSSQL的新手,我想获得一些帮助,为我的Java应用程序创建用户登录并通过JDBC获得连接。到目前为止,我尝试为我的应用程序创建用户登录并使用以下连接字符串,但我根本不工作。任何帮助和提示将不胜感激。

I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.

jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms 
username="shuxer"  password="itarator"


主要有两种使用JDBC的方法 - 使用Windows身份验证和SQL身份验证。 SQL身份验证可能是最简单的。你可以做的是:

There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:

String userName = "username";
String password = "password";

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);

对于Window身份验证,您可以执行以下操作:

For Window authentication you can do something like:

String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);

然后将sqljdbc_auth.dll的路径添加为VM参数(仍然需要sqljdbc4.jar在建立路径)。

and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).

请看一下这里是一个简短的分步指南,展示如何使用jTDS和JDBC从Java连接到SQL Server,如果您需要更多详细信息。希望它有所帮助!

Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!