java连接mysql数据库
时间: 2023-07-11 08:50:16 浏览: 24
下面是使用Java连接MySQL数据库的基本步骤:
1. 下载并安装MySQL数据库及其驱动程序,例如MySQL Connector/J。
2. 在Java代码中加载MySQL驱动程序,例如:
```
Class.forName("com.mysql.jdbc.Driver");
```
3. 创建一个连接到MySQL数据库的Connection对象,例如:
```
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "username";
String password = "password";
Connection conn = DriverManager.getConnection(url, user, password);
```
其中,url是连接字符串,指定MySQL服务器的IP地址、端口号和要连接的数据库名。
4. 创建一个执行SQL语句的Statement对象,例如:
```
Statement stmt = conn.createStatement();
```
5. 执行SQL查询语句,例如:
```
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
```
其中,mytable是要查询的表名。
6. 处理查询结果,例如:
```
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("id=" + id + ", name=" + name);
}
```
7. 关闭结果集、语句和连接,例如:
```
rs.close();
stmt.close();
conn.close();
```