java连接mysql数据库
时间: 2023-07-11 12:33:14 浏览: 36
要连接 MySQL 数据库,可以使用 Java 提供的 JDBC API。以下是连接 MySQL 数据库的基本步骤:
1.导入 JDBC 驱动程序:在代码中导入 MySQL 的 JDBC 驱动程序,例如:`Class.forName("com.mysql.jdbc.Driver");`
2.创建数据库连接:使用 `DriverManager.getConnection()` 方法创建与数据库的连接,例如:`Connection connection = DriverManager.getConnection(url, username, password);`
3.创建 SQL 语句:使用 `connection.createStatement()` 方法创建 Statement 对象,然后使用 Statement 对象的 `executeQuery()` 或 `executeUpdate()` 方法执行 SQL 语句。
4.处理查询结果:如果执行的是 SELECT 语句,可以通过 ResultSet 对象获取查询结果。
5.关闭连接:使用 `connection.close()` 方法关闭与数据库的连接。
下面是一个简单的示例代码:
```java
import java.sql.*;
public class MySQLConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
```
其中,`url` 是数据库的 URL,`username` 和 `password` 是登录数据库的用户名和密码。在这个示例中,我们执行了一个 SELECT 语句,查询了 users 表的所有数据,并将查询结果输出到控制台。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)