Java-তে JDBC ব্যবহার করে MySQL ডেটাবেসে ডেটা ইনসার্ট করতে INSERT` কমান্ড এবং Statement`/`PreparedStatement` ব্যবহার করুন।
টেবিল তৈরি
mysql> CREATE TABLE InsertDemo (
-> Id INT,
-> Name VARCHAR(200),
-> Age INT
-> );
Java কোড (JDBC)
import java.sql.*;
public class JavaInsertDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver"); // আধুনিক: com.mysql.cj.jdbc.Driver
conn = DriverManager.getConnection("jdbc:mysql://localhost/business", "Manish", "123456");
System.out.println("Connection created successfully");
stmt = conn.createStatement();
String query1 = "INSERT INTO InsertDemo VALUES (1, 'John', 34)";
stmt.executeUpdate(query1);
query1 = "INSERT INTO InsertDemo VALUES (2, 'Carol', 42)";
stmt.executeUpdate(query1);
System.out.println("Record inserted successfully");
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try { if (stmt != null) stmt.close(); } catch (SQLException se) {}
try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); }
}
System.out.println("Please check MySQL table.");
}
}
ফলাফল যাচাই
mysql> SELECT * FROM InsertDemo;
+------+-------+------+ | Id | Name | Age | +------+-------+------+ | 1 | John | 34 | | 2 | Carol | 42 | +------+-------+------+
সিকিউরিটি টিপ: প্রোডাকশনে সবসময় PreparedStatement` ব্যবহার করুন SQL ইনজেকশন প্রতিরোধে:
PreparedStatement ps = conn.prepareStatement("INSERT INTO InsertDemo VALUES (?, ?, ?)");
ps.setInt(1, 1);
ps.setString(2, "John");
ps.setInt(3, 34);
ps.executeUpdate();