如何从Java连接到MySQL数据库?当数据库位于远程服务器上时,Java正在本地计算机上运行。
答案 0 :(得分:10)
此示例使用MySQL的MM JDBC驱动程序连接到MySQL数据库:
Connection connection = null;
try {
// Load the JDBC driver
String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost";
String mydatabase = "mydatabase";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "username";
String password = "password";
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
}
您需要在MySQL数据库中拥有一个帐户才能运行此示例。要创建帐户,您可以以root用户身份连接到平台上的MySQL数据库,并运行以下命令:
mysql> GRANT SELECT, INSERT, UPDATE, DELETE PRIVILEGES ON *.*
TO username@localhost IDENTIFIED BY 'password' WITH GRANT OPTION;
答案 1 :(得分:4)
JDBC,当然。获取mysql connector-j jar,将其放入类路径中,然后阅读docs。