以下是使用Java代码连接MySQL数据库的示例:

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

public class MySQLConnection {

    public static void main(String[] args) {
        Connection conn = null;

        try {
            // 加载MySQL驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 创建数据库连接
            String url = "jdbc:mysql://localhost:3306/mydb";
            String username = "root";
            String password = "root";
            conn = DriverManager.getConnection(url, username, password);

            // 执行SQL语句
            // ...

            System.out.println("MySQL数据库连接成功!");
        } catch (ClassNotFoundException e) {
            System.out.println("找不到MySQL驱动类!");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("MySQL数据库连接失败!");
            e.printStackTrace();
        } finally {
            try {
                // 关闭数据库连接
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                System.out.println("关闭MySQL数据库连接失败!");
                e.printStackTrace();
            }
        }
    }

}

这段代码中,首先使用Class.forName()方法加载MySQL驱动类。然后,使用DriverManager.getConnection()方法创建数据库连接,其中需要传入数据库的URL、用户名和密码。最后,可以通过Connection对象执行SQL语句。最后,使用Connection.close()方法关闭数据库连接。

用java代码实现mysql数据库链接

原文地址: https://www.cveoy.top/t/topic/bAHH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录