在Java編程中,JDBC模塊是一個重要的模塊,可以連接資料庫並進行各種操作。其中,插入操作(Insert)是資料庫中最常見的操作之一。本文將詳細介紹在Java中如何使用JDBC模塊進行數據插入的操作。
一、準備工作
在使用JDBC進行資料庫操作前,需要先在項目中引入相應的資料庫連接驅動包。以MySQL資料庫為例,可以在Maven中添加以下依賴:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.26</version> </dependency>
引入依賴後,還需要在代碼中載入資料庫驅動:
Class.forName("com.mysql.cj.jdbc.Driver");
二、建立資料庫連接
在進行資料庫操作前,需要先創建資料庫連接。可以通過以下代碼實現:
String url = "jdbc:mysql://localhost:3306/test_db"; String user = "root"; String password = "123456"; Connection conn = DriverManager.getConnection(url, user, password);
其中,url為資料庫的連接地址,user和password分別為資料庫的用戶名和密碼。
三、編寫SQL語句
在進行數據插入操作時,需要先編寫SQL語句。例如向表中插入一條記錄,可以編寫以下SQL語句:
String sql = "INSERT INTO student (name, age, gender) VALUES (?, ?, ?)";
其中,student為表名,name、age、gender為表的欄位名,?為佔位符。
四、設置參數
在編寫完SQL語句後,還需要設置佔位符的值。可以通過以下代碼實現:
PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Tom"); pstmt.setInt(2, 20); pstmt.setString(3, "male");
其中,setString(int parameterIndex, String x)方法用於設置字元串類型的佔位符,setInt(int parameterIndex, int x)用於設置整型類型的佔位符。
五、執行SQL語句
設置參數後,即可執行SQL語句。可以通過以下代碼實現:
pstmt.executeUpdate();
其中,executeUpdate()方法用於執行SQL語句。
六、關閉資料庫連接
操作完成後,需要關閉資料庫連接。可以通過以下代碼實現:
pstmt.close(); conn.close();
其中,close()方法用於關閉PreparedStatement和Connection對象。
完整代碼示例:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class JdbcInsertDemo { public static void main(String[] args) throws Exception { // 1. 載入資料庫驅動 Class.forName("com.mysql.cj.jdbc.Driver"); // 2. 建立資料庫連接 String url = "jdbc:mysql://localhost:3306/test_db"; String user = "root"; String password = "123456"; Connection conn = DriverManager.getConnection(url, user, password); // 3. 編寫SQL語句 String sql = "INSERT INTO student (name, age, gender) VALUES (?, ?, ?)"; // 4. 設置參數 PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, "Tom"); pstmt.setInt(2, 20); pstmt.setString(3, "male"); // 5. 執行SQL語句 pstmt.executeUpdate(); // 6. 關閉資料庫連接 pstmt.close(); conn.close(); } }
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/249012.html