java连接mysql数据库代码
时间: 2023-06-23 15:55:00 浏览: 91
java中连接mysql数据库代码
5星 · 资源好评率100%
以下是Java连接MySQL数据库的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnection {
public static void main(String[] args) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connection to MySQL database has been established!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
System.out.println("Connection to MySQL database has been closed!");
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
}
```
请将 `your_database_name`、`your_username`、`your_password` 分别替换为实际的数据库名、用户名和密码。
阅读全文