Java 连接 MySQL 数据库示例代码
import java.sql.*;
public class MySQLConnector {
public static void main(String[] args) {
Connection conn = null;
try {
// 加载MySQL驱动程序
Class.forName('com.mysql.jdbc.Driver');
// 获取连接
String url = 'jdbc:mysql://localhost:3306/test';
String user = 'root';
String password = '123456';
conn = DriverManager.getConnection(url, user, password);
System.out.println('数据库连接成功!');
} catch (ClassNotFoundException e) {
System.out.println('找不到MySQL驱动程序!');
e.printStackTrace();
} catch (SQLException e) {
System.out.println('数据库连接失败!');
e.printStackTrace();
} finally {
try {
if (conn != null)
conn.close();
System.out.println('数据库连接已关闭!');
} catch (SQLException e) {
e.printStackTrace();
}
}
}
原文地址: https://www.cveoy.top/t/topic/mNSS 著作权归作者所有。请勿转载和采集!