jdbc连接mysql数据库
时间: 2023-11-21 15:58:08 浏览: 111
以下是使用JDBC连接MySQL数据库的步骤:
1. 下载并安装MySQL数据库,确保数据库已经启动。
2. 下载并安装Java开发环境(JDK)。
3. 下载并安装MySQL JDBC驱动程序。
4. 在Java代码中导入MySQL JDBC驱动程序。
5. 使用JDBC API连接到MySQL数据库。
6. 执行SQL查询或更新。
下面是一个简单的Java程序,演示如何使用JDBC连接MySQL数据库并执行查询:
```java
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
try {
// 加载MySQL JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接到MySQL数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 创建一个Statement对象
Statement stmt = conn.createStatement();
// 执行SQL查询
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println("id: " + id + ", name: " + name + ", email: " + email);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![png](https://img-home.csdnimg.cn/images/20210720083516.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)