简体   繁体   English

如何将 Java 连接到 Microsoft SQL 服务器

[英]How to connect Java to Microsoft SQL server

I made a Java application to connect to a MySQL database.我制作了一个 Java 应用程序来连接到 MySQL 数据库。 The connection was made ​​in this way:连接是这样建立的:

public class Connection {

    public static Connection getConexao() throws SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //System.out.println("Conectado");
            return DriverManager.getConnection("jdbc:mysql://localhost/world","root", "rootadmin");
        } catch (ClassNotFoundException e) {
            throw new SQLException(e.getMessage());
        }
    }
}

Now I needed to change the connection from MySQL to Microsoft SQL Server 2012 .现在我需要将连接从 MySQL 更改为Microsoft SQL Server 2012

Can anyone help me change the connection to the database?谁能帮我更改与数据库的连接?

Thank you all very much.非常感谢大家。

First of all you will need JDBC drivers for MS SQL Server.首先,您需要 MS SQL Server 的 JDBC 驱动程序。 Either from Microsoft or there are other options like jTDS .来自Microsoft或有其他选项,例如jTDS

Then you should use a connection string like jdbc:sqlserver://ServerName:Port;databaseName=;user=username;password=password;然后你应该使用像jdbc:sqlserver://ServerName:Port;databaseName=;user=username;password=password;这样的连接字符串jdbc:sqlserver://ServerName:Port;databaseName=;user=username;password=password;

Of course your SQL Server should be in mixed mode so you can connect with username and password created on server.当然,您的 SQL Server 应该处于混合模式,以便您可以使用在服务器上创建的用户名和密码进行连接。

Applets run on users' computer, therefore you should open your SQL Server ports to all visitors which is a BAD idea.小程序在用户的计算机上运行,​​因此您应该向所有访问者开放您的 SQL Server 端口,这是一个坏主意。

Make database URL like :

jdbc:mysql://IP address:DatabasePort/DatabaseName,username, password   

public class Connection {

public static Connection getConexao()throws SQLException{
    try{
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/world","root", "rootadmin");

    }catch(ClassNotFoundException e) {
        throw new SQLException(e.getMessage());
    }
}

}

This answer is presented for next visitors on this kind of question.此答案是为此类问题的下一位访问者提供的。 Configuring the java driver connection for SQL Server can be quite confusing for new users.SQL Server配置 java 驱动程序连接可能会让新用户感到困惑。 I'll guide you here through SQL Management Studio (SMSS) :我将通过SQL Management Studio (SMSS)指导您:

There're 2 kinds of authentification accepted on SQL Server. SQL Server 接受两种身份验证。 They are Windows & SQL Server authentification.它们是WindowsSQL Server身份验证。 In this answer I'll active " sa " (syst. administrator) account for quick setup demonstration over the connection.在这个答案中,我将激活“ sa ”(系统管理员)帐户以通过连接进行快速设置演示。

To enable the " sa " account (you can skip this if it had already been there):要启用“ sa ”帐户(如果它已经存在,您可以跳过它):

  • Login as usual using default window authentification mode使用默认窗口身份验证模式照常登录
  • Right click on the server name (ie MYCOMPUTER223\\SQLEXPRESS ) > Security > go enable the SQL Server & Window authentification mode > ok右键单击服务器名称(即MYCOMPUTER223\\SQLEXPRESS )>安全性> 启用SQL Server & Window 身份验证模式> ok
  • On the left tree menu, click Security > Logins > right click that " sa " > Properties > set up your " password " for this " sa " account在左侧树形菜单中,单击安全>登录> 右键单击​​“ sa ” >属性> 为这个“ sa ”帐户设置“密码
  • and then on the left menu there is the " Status "> enable the " Login: "然后在左侧菜单上有“状态”> 启用“登录:
  • restart the SQL Server service重新启动 SQL Server 服务
  • now login as " sa " through " SQL Server authentification mode " on the SMSS .现在通过 SMSS 上的“ SQL Server 身份验证模式”以“ sa身份登录。 Using the password we've just set up.使用我们刚刚设置的密码。

Enable the TCP/IP for the conn.为连接启用 TCP/IP。 instance (this is by default is disabled particularly on sql express editions):实例(这在默认情况下是禁用的,特别是在 sql express 版本上):

  • Open "Sql Server Configuration Manager".打开“Sql Server 配置管理器”。 This is installed along the installation of SQL Server engine.这是在安装 SQL Server 引擎的同时安装的。
  • " SQL Server Network Configuration " > " Protocol for SQLExpress " > enable the " TCP/IP " SQL Server 网络配置”>“ SQLExpress 协议”> 启用“ TCP/IP
  • right click that " TCP/IP " > " IP Address " > scroll down till you find " IPAll " and then just fill the " port " field with 1433右键单击“ TCP/IP ”>“ IP 地址”> 向下滚动直到找到“ IPAll ”,然后用1433填充“端口”字段

You can now use this credential for the SMSS:您现在可以将此凭证用于 SMSS:

username       : sa
 password      : ...the password you've just set up above..

Or you can now use this credential on your external java based clients/data or BI tools/sql management tools such as Pentaho , Heidi SQL , DB Weaver or any particular java framework conn.或者,您现在可以在基于外部 Java 的客户端/数据或BI工具/sql 管理工具(例如PentahoHeidi SQLDB Weaver或任何特定的 Java 框架连接)上使用此凭据。 manager descriptor, etc. :经理描述符等:

hostname      : localhost (or any custome host domains)
database name : your database name..
instance name : i.e SQLEXPRESS (this can be found through the SMSS, right click the server name > view connection properties)
port          : 1433
username      : sa
password      : ...the password you've just set up above..

or via url/uri for the Java connection manager/factory:或通过 url/uri 获取 Java 连接管理器/工厂:

    String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=Yourdatabasename;user=sa;password=yourSApassword";

public Connection createConnection() throws NoSuchAlgorithmException {      
        System.out.println("Creating SQL Server DataBase Connection");
        Connection connection = null; 
        try {  
            // Provide the java database driver
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
            // Provide URL, database and credentials according to your database
            // .getConnection ("url/namadatabase, user, password")
            String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=DummyDatabase;user=sa;password=YourSAaccountpassword";
            connection = DriverManager.getConnection(Connectionurl);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if (connection != null) {
            System.out.println("Connection created successfully..");
        }
        return connection;
    }

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

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