如何在Java中连接MySQL数据库?

当我尝试时,我得到

java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)

Or

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Or

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver

当前回答

初始化数据库常量

创建常量属性数据库用户名,密码,URL和驱动程序,轮询限制等。

// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit

初始化连接和属性

一旦建立了连接,最好将其存储起来以供重用。

// init connection object
private Connection connection;
// init properties object
private Properties properties;

创建属性

属性对象保存连接信息,检查它是否已经设置。

// create properties
private Properties getProperties() {
    if (properties == null) {
        properties = new Properties();
        properties.setProperty("user", USERNAME);
        properties.setProperty("password", PASSWORD);
        properties.setProperty("MaxPooledStatements", MAX_POOL);
    }
    return properties;
}

连接数据库

现在使用已初始化的常量和属性连接到数据库。

// connect database
public Connection connect() {
    if (connection == null) {
        try {
            Class.forName(DATABASE_DRIVER);
            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
        } catch (ClassNotFoundException | SQLException e) {
            // Java 7+
            e.printStackTrace();
        }
    }
    return connection;
}

断开数据库连接

完成数据库操作后,只需关闭连接。

// disconnect database
public void disconnect() {
    if (connection != null) {
        try {
            connection.close();
            connection = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

一切都在一起

在修改database_name,用户名和密码等后直接使用MysqlConnect类。

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

public class MysqlConnect {
    // init database constants
    private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    private static final String MAX_POOL = "250";

    // init connection object
    private Connection connection;
    // init properties object
    private Properties properties;

    // create properties
    private Properties getProperties() {
        if (properties == null) {
            properties = new Properties();
            properties.setProperty("user", USERNAME);
            properties.setProperty("password", PASSWORD);
            properties.setProperty("MaxPooledStatements", MAX_POOL);
        }
        return properties;
    }

    // connect database
    public Connection connect() {
        if (connection == null) {
            try {
                Class.forName(DATABASE_DRIVER);
                connection = DriverManager.getConnection(DATABASE_URL, getProperties());
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    // disconnect database
    public void disconnect() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

如何使用?

初始化数据库类。

// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();

代码中的其他地方……

String sql = "SELECT * FROM `stackoverflow`";
try {
    PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
    ... go on ...
    ... go on ...
    ... DONE ....
} catch (SQLException e) {
    e.printStackTrace();
} finally {
    mysqlConnect.disconnect();
}

这是所有:)如果有任何改善编辑它!希望这对你有帮助。

其他回答

简短而甜蜜的代码。

try {       
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver Loaded");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
    //Database Name - testDB, Username - "root", Password - ""
    System.out.println("Connected...");         
} catch(Exception e) {
    e.printStackTrace();
}

SQL server 2012

try {
    String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123"; 
    //KHILAN is Host    and 1433 is port number     
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    System.out.println("Driver Loaded");
    conn = DriverManager.getConnection(url);
    System.out.println("Connected...");
} catch(Exception e) {
    e.printStackTrace();
}

MySQL JDBC连接与useSSL。

private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");

private String connectToDb() throws Exception {
   String jdbcDriver = "com.mysql.jdbc.Driver";
   String dbUrl = "jdbc:mysql://" + db_server  +
        "?verifyServerCertificate=false" +
        "&useSSL=true" +
        "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
    String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
    ResultSet resultSet = statement.executeQuery(query);
    resultSet.next();
    return resultSet.getString(1);
}

下载JDBC驱动程序

下载链接(选择平台独立):https://dev.mysql.com/downloads/connector/j/

将JDBC驱动程序移动到C驱动器

解压文件并移动到C:\驱动器。你的驱动程序路径应该是C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19

运行Java

java -cp "C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19.jar" testMySQL.java

testMySQL.java

import java.sql.*;
import java.io.*;

public class testMySQL {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
        try
        {  
            Class.forName("com.mysql.cj.jdbc.Driver");  
            Connection con=DriverManager.getConnection(  
                "jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");  
            Statement stmt=con.createStatement();  
            ResultSet rs=stmt.executeQuery("show databases;");  
            System.out.println("Connected");  
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

    }  

}

HOW

设置驱动程序以运行快速示例

1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:

No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

java.lang.ClassNotFoundException: com.mysql.jdbc:Driver

要设置CLASSPATH

方法1:设置CLASSPATH变量。

export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile

在上面的命令中,我已经将CLASSPATH设置为当前文件夹和mysql-connector-java-VERSION.jar文件。因此,当执行java MyClassFile命令时,java应用程序启动器将尝试加载CLASSPATH中的所有java类。 它发现Drive class => BOOM错误消失了。

方法2:

java -cp .:mysql-connector-java-VERSION.jar MyClassFile

注意:forname(“com.mysql.jdbc.Driver”);目前已弃用2019年4月1日。

希望这能帮助到一些人!

你需要在你的类路径中有mysql连接器jar。

在Java中,JDBC API使一切与数据库。我们可以使用JDBC编写Java应用程序 1. 发送查询或更新SQL到DB(任何关系数据库) 2. 从DB中检索和处理结果

通过以下三个步骤,我们可以从任何数据库中检索数据

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

while (rs.next()) {
    int x = rs.getInt("a");
    String s = rs.getString("b");
    float f = rs.getFloat("c");
}