Java JDBC Example: Insert Data into MySQL Database
In this tutorial, you'll learn how to insert data into a MySQL table using Java JDBC. We'll use the PreparedStatement
to safely add new records to the students
table.
इस ट्यूटोरियल में आप सीखेंगे कि Java JDBC की मदद से MySQL टेबल में डेटा कैसे insert करें। हम PreparedStatement
का उपयोग करके students
टेबल में नया रिकॉर्ड जोड़ेंगे।
Prerequisites
- MySQL server running on your system
- A database named
studentdb
- A table named
students
with columnsid
(INT, AUTO_INCREMENT) andname
(VARCHAR)
- आपके सिस्टम पर चल रहा MySQL सर्वर
studentdb
नाम का डेटाबेसstudents
नाम की टेबल जिसमेंid
(INT, AUTO_INCREMENT) औरname
(VARCHAR) कॉलम हों
SQL to create table:
टेबल बनाने का SQL:
CREATE DATABASE studentdb;
USE studentdb;
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100)
);
Java Code to Insert Data
This Java code connects to MySQL and inserts a new student name using PreparedStatement
.
यह Java कोड MySQL से कनेक्ट करता है और PreparedStatement
का उपयोग करके नया छात्र नाम insert करता है।
import java.sql.*;
public class JdbcInsertExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/studentdb";
String user = "root";
String password = "your_mysql_password";
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create connection
Connection con = DriverManager.getConnection(url, user, password);
// Prepare SQL INSERT statement
String sql = "INSERT INTO students (name) VALUES (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
// Set the value to insert
pstmt.setString(1, "Neha");
// Execute the insert
int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + " record(s) inserted.");
// Close connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation
Class.forName
: Loads the MySQL JDBC driver.DriverManager.getConnection
: Connects to the database.PreparedStatement
: Helps execute parameterized SQL safely.pstmt.setString(1, "Neha")
: Sets the value for the SQL parameter.executeUpdate()
: Executes the INSERT query.
Class.forName
: MySQL JDBC ड्राइवर लोड करता है।DriverManager.getConnection
: डेटाबेस से कनेक्शन बनाता है।PreparedStatement
: पैरामीटराइज्ड SQL सुरक्षित रूप से execute करता है।pstmt.setString(1, "Neha")
: SQL parameter के लिए मान सेट करता है।executeUpdate()
: INSERT query को चलाता है।
Expected Output
1 record(s) inserted.
This confirms that one new record has been added to the students
table.
यह पुष्टि करता है कि students
टेबल में एक नया रिकॉर्ड जोड़ा गया है।