如何在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

当前回答

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);
}

其他回答

初始化数据库常量

创建常量属性数据库用户名,密码,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();
}

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

下面是如何安装MySQL和JDBC以及如何使用它的一步一步的解释:

Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here). If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties. If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application. java -cp .;/path/to/mysql-connector.jar com.example.YourClass The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well. CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; Create a user for Java and grant it access. Simply because using root is a bad practice. CREATE USER 'java'@'localhost' IDENTIFIED BY 'password'; GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password'; Yes, java is the username and password is the password here. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax: jdbc:mysql://hostname:port/databasename hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config. port: The TCP/IP port where MySQL server listens on. This is by default 3306. databasename: The name of the database you'd like to connect to. That's javabase. So the final URL should look like: jdbc:mysql://localhost:3306/javabase Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection. String url = "jdbc:mysql://localhost:3306/javabase"; String username = "java"; String password = "password"; System.out.println("Connecting database..."); try (Connection connection = DriverManager.getConnection(url, username, password)) { System.out.println("Database connected!"); } catch (SQLException e) { throw new IllegalStateException("Cannot connect the database!", e); } If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below: System.out.println("Loading driver..."); try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver loaded!"); } catch (ClassNotFoundException e) { throw new IllegalStateException("Cannot find the driver in the classpath!", e); } Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath. Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough. If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes: IP address or hostname in JDBC URL is wrong. Hostname in JDBC URL is not recognized by local DNS server. Port number is missing or wrong in JDBC URL. DB server is down. DB server doesn't accept TCP/IP connections. DB server has run out of connections. Something in between Java and DB is blocking connections, e.g. a firewall or proxy. To solve the one or the other, follow the following advices: Verify and test them with ping. Refresh DNS or use IP address in JDBC URL instead. Verify it based on my.cnf of MySQL DB. Start the DB. Verify if mysqld is started without the --skip-networking option. Restart the DB and fix your code accordingly that it closes connections in finally. Disable firewall and/or configure firewall/proxy to allow/forward the port. Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.

就连通性而言,这就是问题所在。您可以在这里找到一个更高级的教程,如何在基本DAO类的帮助下在数据库中加载和存储完全有价值的Java模型对象。


对DB连接使用单例模式是一种糟糕的方法。请参见其他问题:在多线程系统中使用静态java.sql.Connection实例安全吗?这是第一个错误。

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日。

希望这能帮助到一些人!

简短而甜蜜的代码。

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();
}

我之前用过连接,它看起来是最简单的方法,但也有建议在if语句中使用

Connection con = DriverManager.getConnection(
                     "jdbc:myDriver:DatabaseName",
                     dBuserName,
                     dBuserPassword);
if (con != null){
 //..handle your code there 
}

或者类似的方式:)

可能在某些情况下,getConnection可以返回null:)