温馨提示×

jdbc增删改查代码怎么写

小亿
84
2024-04-09 16:48:08
栏目: 编程语言

下面是一个简单的示例代码,演示如何使用JDBC进行增删改查操作:

1、增加数据:

```java

Connection conn = DriverManager.getConnection(url, username, password);

String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";

PreparedStatement stmt = conn.prepareStatement(sql);

stmt.setString(1, "value1");

stmt.setString(2, "value2");

stmt.executeUpdate();

conn.close();

```

2、删除数据:

```java

Connection conn = DriverManager.getConnection(url, username, password);

String sql = "DELETE FROM table_name WHERE column1 = ?";

PreparedStatement stmt = conn.prepareStatement(sql);

stmt.setString(1, "value1");

stmt.executeUpdate();

conn.close();

```

3、更新数据:

```java

Connection conn = DriverManager.getConnection(url, username, password);

String sql = "UPDATE table_name SET column1 = ? WHERE column2 = ?";

PreparedStatement stmt = conn.prepareStatement(sql);

stmt.setString(1, "new_value");

stmt.setString(2, "value2");

stmt.executeUpdate();

conn.close();

```

4、查询数据:

```java

Connection conn = DriverManager.getConnection(url, username, password);

String sql = "SELECT * FROM table_name WHERE column1 = ?";

PreparedStatement stmt = conn.prepareStatement(sql);

stmt.setString(1, "value1");

ResultSet rs = stmt.executeQuery();

while (rs.next()) {

System.out.println(rs.getString("column1"));

System.out.println(rs.getString("column2"));

}

conn.close();

```

请注意,以上示例代码是基于JDBC API,需要导入相应的包,并且需要替换相应的url、username、password、table_name、column和value等信息。

0