java连接mysql5.7
时间: 2023-10-24 19:08:24 浏览: 185
要在Java中连接MySQL 5.7,你可以按照以下步骤进行操作:
1. 导入MySQL连接驱动包:
```
import java.sql.*;
```
2. 加载并注册MySQL驱动程序:
```
Class.forName("com.mysql.cj.jdbc.Driver");
```
3. 创建连接字符串:
```
String url = "jdbc:mysql://localhost:3306/database_name?characterEncoding=utf-8";
String username = "your_username";
String password = "your_password";
```
4. 建立与数据库的连接:
```
Connection connection = DriverManager.getConnection(url, username, password);
```
5. 创建Statement对象来执行SQL语句:
```
Statement statement = connection.createStatement();
```
6. 执行SQL查询或更新操作:
```
String sql = "SELECT * FROM table_name";
ResultSet resultSet = statement.executeQuery(sql);
// 或者
String sql = "UPDATE table_name SET column_name = 'value' WHERE condition";
int rowsAffected = statement.executeUpdate(sql);
```
7. 处理结果或关闭连接:
```
while (resultSet.next()) {
// 处理查询结果
}
resultSet.close();
statement.close();
connection.close();
```
阅读全文