如何将 MySQL 连接到 Java 程序

2022-01-24 00:00:00 connection mysql jdbc java

我已经安装了 MySQL(上次更新).我需要编码,这将创建 &与 SQL DB 建立连接&管理数据库(使用 SELECT、INSERT、CREATE).

I ve installed MySQL (last update). I need to code, that ll create & establish a connection with SQL DB & manage the DB(using SELECT, INSERT, CREATE).

我做了所有事情,但是我无法创建连接.我还安装了 MySQL/J 连接器,我只是将 .zip 包解压缩到一个文件夹 &在Variables中添加了文件夹路径).

I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).

谁能告诉我下一行中的 URL 是指 wat 吗?

Can anyone tell me wat is meant by URL in the below line?

Connection connection = DriverManager.getConnection(url, username, password);

我试过这个:

String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");

但它不起作用.我无法理解URL"一词.谁能解释一下,'url'和wat的含义应该通过Java连接到SQL服务器.

But it's not working. I am unable able to understand the term 'URL'. Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.

更新:

这是完整的代码.它仍然无法连接.

This is the Full code. It still cannot connect.

import java.sql.*;

public class TestDriver {

public static void main(String[] args) {
try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection
    System.out.println("Driver Loaded Succesfully");
}
catch (Exception e){
    System.out.println("Unable to Load Driver!!!");
}

try {
    Class.forName(com.mysql.jdbc.Driver");  // initialise the driver
    String url ="jdbc:mysql://localhost:3306/myfirstdb";
    Connection con = DriverManager.getConnection(url, "root", "1234");
    System.out.println("connection Established");
    }
    catch(Exception e) {
                System.out.println("Couldnt get connection");
    }
    }
}

你能告诉我 MySQL Connector/J 的用途是什么吗?

Can you tell me wat is the purpose of MySQL Connector/J?

推荐答案

在问题中,您似乎正在使用带有 SQL Server jdbc URL 的 MySQL jdbc 驱动程序.这行不通.

In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.

如果您使用的是 MySQL 数据库:

If you are using a MySQL database:

Class.forName("com.mysql.jdbc.Driver");  // initialise the driver

String url ="jdbc:mysql://localhost:3306/myfirstdb";

如果您使用的是 SQL Server 数据库,您将需要一个完全不同的 jdbc 驱动程序.jTDS 是开源的,是一个不错的选择.在您的类路径中包含 jtds.jar 文件并使用如下内容:

If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:

Class.forName("net.sourceforge.jtds.jdbc.Driver");  // initialise the driver

String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";

相关文章