在 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>