如何安装JDBC以及如何使用它连接到mysql?

Mah*_*oud 5 java jdbc

我正在尝试安装JDBC,但我不知道如何,当你只有jar文件时,我将它复制到我的java ext文件夹,但它一直给我一个错误,谁能告诉我如何完成安装驱动程序并使用它?

下面是我使用的代码

import java.sql.*;
   public class Test1
   {
       public static void main (String[] args)
       {
String url = "jdbc:mysql://localhost:3306/sabayafr_sabmah";
String username = "root";
String password = "ma";
Connection connection = null;
try {
    System.out.println("Connecting database...");
    connection = DriverManager.getConnection(url, username, password);
    System.out.println("Database connected!");
} catch (SQLException e) {
    System.err.println("Cannot connect the database!");
    e.printStackTrace();
} finally {
    System.out.println("Closing the connection.");
    if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}

       }
   }
Run Code Online (Sandbox Code Playgroud)

以下是我得到的回应

Cannot connect to database server
Run Code Online (Sandbox Code Playgroud)

更新#3

C:\Users\AlAsad\Desktop>java -cp .;mysql-connector-java-5.0.8-bin.jar Test1
Connecting database...
Cannot connect the database!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
sabayafr_sabmah
        at java.sql.DriverManager.getConnection(Unknown Source)
        at java.sql.DriverManager.getConnection(Unknown Source)
        at Test1.main(Test1.java:12)
Closing the connection.
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 9

您正在尝试将MySQL与专为Microsoft SQL Server设计的jTDS JDBC驱动程序的URL 连接.这永远不会奏效.即使不是通过将JAR文件放在类路径中来修复当前问题.

你真的需要MySQL JDBC驱动程序.另请参阅此答案以获得简短但完整的教程

  • 您需要将包含JDBC驱动程序的JAR文件添加到运行时类路径中.链接的答案详细解释了这一点.如果您使用的是IDE,只需将JAR文件作为*Library*添加到*Build Path*即可.如果你正在使用`java.exe`,那么你需要在`-cp`参数中指定它的路径.路径应该是绝对的,例如`c:/ path/to/mysql-connector.jar`或相对于当前工作目录,例如`mysql-connector.jar`,当JAR文件位于执行的同一文件夹中时`java.exe`. (2认同)
  • 运行`Class.forName("com.mysql.jdbc.Driver");`*before*`DriverManager#getConnection()`call.它位于链接答案中的单独"try"块中.请深呼吸,小心地从上到下采取步骤.不要着急;) (2认同)