简体   繁体   English

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

[英]How do I connect to a SQL Server 2008 database using JDBC?

I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database.我在本地 PC 上安装了 MSSQL 2008,我的 Java 应用程序需要连接到 MSSQL 数据库。 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.我是 MSSQL 的新手,我希望在为我的 Java 应用程序创建用户登录和通过 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"

There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. JDBC的使用主要有两种方式——使用Windows认证和SQL认证。 SQL authentication is probably the easiest. SQL 身份验证可能是最简单的。 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);

after adding sqljdbc4.jar to the build path.将 sqljdbc4.jar 添加到构建路径后。

For Window authentication you can do something like:对于 Window 身份验证,您可以执行以下操作:

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

and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).然后将 sqljdbc_auth.dll 的路径添加为 VM 参数(构建路径中仍需要 sqljdbc4.jar)。

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.如果您需要更多详细信息,请查看此处的简短分步指南,其中显示了如何使用 jTDS 和 JDBC 从 Java 连接到 SQL Server。 Hope it helps!希望能帮助到你!

You can use this :你可以使用这个

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectMSSQLServer
{
   public void dbConnect(String db_connect_string,
            String db_userid,
            String db_password)
   {
      try {
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection conn = DriverManager.getConnection(db_connect_string,
                  db_userid, db_password);
         System.out.println("connected");
         Statement statement = conn.createStatement();
         String queryString = "select * from sysobjects where type='u'";
         ResultSet rs = statement.executeQuery(queryString);
         while (rs.next()) {
            System.out.println(rs.getString(1));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args)
   {
      ConnectMSSQLServer connServer = new ConnectMSSQLServer();
      connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
               "<password>");
   }
}

I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.我也在使用 mssql server 2008 和 jtds。在我的情况下,我使用以下连接字符串并且它可以工作。

Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip     
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();

If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening.如果您在连接时遇到问题,最有可能的问题是您尚未在端口 1433 上启用 TCP/IP 侦听器。快速的“netstat -an”命令将告诉您它是否正在侦听。 By default, SQL server doesn't enable this after installation.默认情况下,SQL 服务器在安装后不启用此功能。

Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).此外,您需要在“sa”帐户上设置密码并启用“sa”帐户(如果您打算使用该帐户进行连接)。

Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.显然,这也意味着您需要在 MSSQL 节点上启用“混合模式身份验证”。

Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms;尝试这样使用:jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName实例=实例名称

I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress不知道你用的是哪个版本的mssql,如果是express版本,默认实例是sqlexpress

Do not forget check if SQL Server Browser service is running.不要忘记检查 SQL Server Browser 服务是否正在运行。

You can try configure SQL server:您可以尝试配置 SQL 服务器:

  1. Step 1: Open SQL server 20xx Configuration Manager第 1 步:打开 SQL Server 20xx 配置管理器
  2. Step 2: Click Protocols for SQL.. in SQL server configuration.步骤 2:单击 SQL 服务器配置中的 Protocols for SQL..。 Then, right click TCP/IP, choose Properties然后,右键单击 TCP/IP,选择属性
  3. Step 3: Click tab IP Address, Edit All TCP.步骤 3:单击选项卡 IP 地址,编辑所有 TCP。 Port is 1433端口是 1433

NOTE: ALL TCP port is 1433 Finally, restart the server.注意:所有 TCP 端口都是 1433 最后,重新启动服务器。

Simple Java Program which connects to the SQL Server.连接到 SQL Server 的简单 Java 程序。

NOTE: You need to add sqljdbc.jar into the build path注意:您需要将 sqljdbc.jar 添加到构建路径中

// localhost : local computer acts as a server // localhost : 本地计算机充当服务器

// 1433 : SQL default port number // 1433 : SQL 默认端口号

// username : sa // 用户名:sa

// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root' // 密码:使用密码,安装SQL server management studio时使用,我这里是'root'

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

    public class Conn {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {

            Connection conn=null;
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
                conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");

                if(conn!=null)
                    System.out.println("Database Successfully connected");

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

Try this.尝试这个。

import java.sql.Connection;导入 java.sql.Connection;

import java.sql.DriverManager;导入 java.sql.DriverManager;

import java.sql.ResultSet;导入 java.sql.ResultSet;

import java.sql.Statement;导入 java.sql.Statement;

public class SQLUtil {公共类 SQLUtil {

public void dbConnect(String db_connect_string,String db_userid, String db_password) {公共无效dbConnect(字符串db_connect_string,字符串db_userid,字符串db_password){

try {尝试 {

 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password); System.out.println("connected"); Statement statement = conn.createStatement(); String queryString = "select * from cpl"; ResultSet rs = statement.executeQuery(queryString); while (rs.next()) { System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); } }

public static void main(String[] args) {公共静态无效主(字符串 [] args){

SQLUtil connServer = new SQLUtil(); SQLUtil connServer = new SQLUtil();

connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB", "sa", "0123"); connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB", "sa", "0123");

} }

} }

Try this尝试这个

 Class.forName( "net.sourceforge.jtds.jdbc.Driver" );

String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM