jdbc增删查改代码
时间: 2024-02-18 10:57:20 浏览: 72
以下是一个简单的JDBC增删查改的示例代码:
1. 建立数据库连接:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
```
2. 添加数据:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertData {
public static void main(String[] args) {
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "John");
stmt.setInt(2, 25);
stmt.executeUpdate();
System.out.println("Data inserted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
3. 删除数据:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteData {
public static void main(String[] args) {
String sql = "DELETE FROM users WHERE id = ?";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, 1);
stmt.executeUpdate();
System.out.println("Data deleted successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
4. 修改数据:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateData {
public static void main(String[] args) {
String sql = "UPDATE users SET age = ? WHERE id = ?";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, 30);
stmt.setInt(2, 1);
stmt.executeUpdate();
System.out.println("Data updated successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
5. 查询数据:
```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) {
String sql = "SELECT * FROM users";
try (Connection conn = DatabaseConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
阅读全文