java实现与MySQL内的表格的增删改查
时间: 2024-03-05 13:50:10 浏览: 14
Java可以通过JDBC连接MySQL数据库,在Java程序中实现对MySQL内的表格的增删改查。以下是一个简单的示例:
1. 导入JDBC驱动:
```java
Class.forName("com.mysql.cj.jdbc.Driver");
```
2. 建立与MySQL数据库的连接:
```java
String url = "jdbc:mysql://localhost:3306/dbname?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(url, "username", "password");
```
其中,`url`为MySQL数据库的连接地址,`username`和`password`为连接数据库的用户名和密码。
3. 在Java程序中实现对MySQL内表格的增删改查,例如:
查询:
```java
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM tablename");
while(rs.next()) {
//处理查询结果
}
```
插入:
```java
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO tablename (col1, col2, col3) VALUES (?, ?, ?)");
pstmt.setString(1, "value1");
pstmt.setString(2, "value2");
pstmt.setInt(3, 3);
int count = pstmt.executeUpdate();
```
更新:
```java
PreparedStatement pstmt = conn.prepareStatement("UPDATE tablename SET col1 = ?, col2 = ? WHERE id = ?");
pstmt.setString(1, "newvalue1");
pstmt.setString(2, "newvalue2");
pstmt.setInt(3, 1);
int count = pstmt.executeUpdate();
```
删除:
```java
PreparedStatement pstmt = conn.prepareStatement("DELETE FROM tablename WHERE id = ?");
pstmt.setInt(1, 1);
int count = pstmt.executeUpdate();
```
其中,`PreparedStatement`是预编译的SQL语句对象,可以防止SQL注入攻击。执行SQL语句时,可以使用`executeQuery()`方法执行查询语句,使用`executeUpdate()`方法执行插入、更新和删除语句。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)
![](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)