java的增删改查代码_Java增删改查代码
时间: 2023-11-02 15:06:41 浏览: 100
java增删查改代码生成器.zip
5星 · 资源好评率100%
以下是Java实现增删改查的示例代码:
### 连接数据库
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
private static final String USER = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
### 增加数据
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddData {
public static void main(String[] args) {
Connection conn = DBUtil.getConnection();
String sql = "INSERT INTO user (username, password, age) VALUES (?, ?, ?)";
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "Tom");
pstmt.setString(2, "123456");
pstmt.setInt(3, 20);
int result = pstmt.executeUpdate();
System.out.println("添加了" + result + "条数据!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
### 删除数据
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteData {
public static void main(String[] args) {
Connection conn = DBUtil.getConnection();
String sql = "DELETE FROM user WHERE id=?";
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 1);
int result = pstmt.executeUpdate();
System.out.println("删除了" + result + "条数据!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
### 修改数据
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateData {
public static void main(String[] args) {
Connection conn = DBUtil.getConnection();
String sql = "UPDATE user SET age=? WHERE id=?";
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 21);
pstmt.setInt(2, 2);
int result = pstmt.executeUpdate();
System.out.println("修改了" + result + "条数据!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
### 查询数据
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class QueryData {
public static void main(String[] args) {
Connection conn = DBUtil.getConnection();
String sql = "SELECT * FROM user";
PreparedStatement pstmt;
ResultSet rs;
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("id:" + rs.getInt("id") + ",username:" + rs.getString("username") + ",password:" + rs.getString("password") + ",age:" + rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
阅读全文