java连接MySQL数据库
时间: 2023-09-04 11:09:31 浏览: 100
可以使用Java中的JDBC(Java Database Connectivity)API来连接MySQL数据库。以下是一个简单的Java程序示例,用于连接MySQL数据库:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "mypassword";
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish a connection to the database
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database!");
// Perform database operations here...
// Close the database connection
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在此示例中,我们首先加载MySQL JDBC驱动程序,然后使用`DriverManager.getConnection()`方法建立与数据库的连接。要更改数据库连接URL,您需要替换“mydatabase”为您自己的数据库名称,然后替换“root”和“mypassword”为您的数据库用户名和密码。
阅读全文
相关推荐









