java 代码连接mysql数据库
时间: 2024-03-23 09:35:30 浏览: 18
在Java中连接MySQL数据库可以使用JDBC(Java Database Connectivity)技术。以下是一个简单的示例代码来连接MySQL数据库:
```java
import java.sql.*;
public class MySQLConnectionExample {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
// 声明连接对象
Connection conn = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection(url, username, password);
// 执行SQL查询
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// 关闭结果集、语句和连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请确保你已经下载并安装了MySQL的JDBC驱动程序,并将其添加到你的项目中。在上述代码中,你需要将`url`、`username`和`password`替换为你自己的数据库连接信息。