在 Java 中使用 JDBC 实现增删改查的步骤如下:
1. 导入 JDBC 相关的包和类:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
2. 建立数据库连接:
String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "123456"; Connection conn = null; try {????conn?=?DriverManager.getConnection(url,?username,?password); }?catch?(SQLException?e)?{
????e.printStackTrace(); }
3. 创建 SQL 语句并预编译:
String?sql?=?“SELECT?*?FROM?mytable?WHERE?id?=??”; PreparedStatement?pstmt?=?conn.prepareStatement(sql);
4. 设置参数并执行查询:
int?id?=?1; pstmt.setInt(1,?id); ResultSet?rs?=?pstmt.executeQuery();
5. 遍历结果集:
while?(rs.next())?{????int?id?=?rs.getInt(“id”);
????String?name?=?rs.getString(“name”);
????System.out.println("ID:?"?+?id?+?",?Name:?"?+?name); }
6. 关闭数据库连接和结果集:
rs.close(); pstmt.close(); conn.close();
上述代码演示的是查询操作,若要实现增删改,只需将 SQL 语句和执行方法进行相应的修改。
- 增加数据:
String?sql?=?“INSERT?INTO?mytable?(id,?name)?VALUES?(?,??)”; PreparedStatement?pstmt?=?conn.prepareStatement(sql); int?id?=?1; String?name?=?“John?Doe”; pstmt.setInt(1,?id); pstmt.setString(2,?name); int?rows?=?pstmt.executeUpdate();
- 删除数据:
String?sql?=?“DELETE?FROM?mytable?WHERE?id?=??”; PreparedStatement?pstmt?=?conn.prepareStatement(sql); int?id?=?1; pstmt.setInt(1,?id); int?rows?=?pstmt.executeUpdate();- 修改数据: ```java String sql = "UPDATE mytable SET name = ? WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); int id = 1; String name = "Jane Doe"; pstmt.setString(1, name); pstmt.setInt(2, id); int rows = pstmt.executeUpdate();</pre><p>以上是使用 JDBC 实现增删改查的基本步骤,具体的操作可以根据需求进行调整和扩展。<br/></p>
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java多态的实现方式有哪些