0% found this document useful (0 votes)
2 views2 pages

Program 29

This Java program demonstrates how to insert a new student record into a MySQL database using JDBC. It establishes a connection to a database named 'testdb', prompts the user for a student's name and age, and executes an SQL insert statement. Finally, it ensures that resources are closed properly after the operation.

Uploaded by

udayd1016
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Program 29

This Java program demonstrates how to insert a new student record into a MySQL database using JDBC. It establishes a connection to a database named 'testdb', prompts the user for a student's name and age, and executes an SQL insert statement. Finally, it ensures that resources are closed properly after the operation.

Uploaded by

udayd1016
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import [Link].

Connection;

import [Link];

import [Link];

import [Link];

import [Link];

public class JdbcInsertExample {

public static void main(String[] args) {

// Database credentials

String url = "jdbc:mysql://localhost:3306/testdb"; // database name: testdb

String user = "root"; // your MySQL username

String password = "admin"; // your MySQL password

Connection conn = null;

PreparedStatement pstmt = null;

Scanner sc = new Scanner([Link]);

try {

// Step 1: Load JDBC driver

[Link]("[Link]");

// Step 2: Establish connection

conn = [Link](url, user, password);

[Link]("Connected to the database successfully!");

// Step 3: Prepare SQL Insert Statement

String sql = "INSERT INTO students (name, age) VALUES (?, ?)";

pstmt = [Link](sql);

[Link]("Enter name of student: ");

String name = [Link]();


[Link]("Age: ");

int age = [Link]();

[Link]();

// Step 4: Set parameter values

[Link](1, name);

[Link](2, age);

// Step 5: Execute update

int rowsInserted = [Link]();

if (rowsInserted > 0) {

[Link]("A new student was inserted successfully!");

} catch (Exception e) {

[Link]();

} finally {

// Step 6: Close resources

try { if (pstmt != null) [Link](); } catch (SQLException e) {}

try { if (conn != null) [Link](); } catch (SQLException e) {}

You might also like