File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
insert_data_into_database Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ # Insert data into database using JDBC.
2+ ```
3+ package insertData;
4+
5+ import java.sql.Connection;
6+ import java.sql.DriverManager;
7+ import java.sql.PreparedStatement;
8+ import java.util.Scanner;
9+
10+ public class insertData {
11+
12+ private static Scanner sc;
13+
14+ public static void main(String[] args) throws Exception { // throws Exception is used to handle the exception without using try-catch block
15+
16+ sc = new Scanner(System.in);
17+ System.out.println("Enter the student details: ");
18+ System.out.print("Enter the student id: ");
19+ int id = sc.nextInt();
20+ System.out.print("Enter the student name: ");
21+ String name = sc.next();
22+ System.out.print("Enter the student branch: ");
23+ String branch = sc.next();
24+
25+ Class.forName("com.mysql.cj.jdbc.Driver"); // load and register the driver
26+
27+ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/jdbc_db", "root", "Akash@123"); // establish the connection
28+
29+ PreparedStatement ps = connection.prepareStatement("insert into student values('"+id+"','"+name+"','"+branch+"')"); // execute the query")
30+
31+ int i = ps.executeUpdate(); // execute the query
32+ if (i > 0) // if the record is inserted successfully then it will return 1 else 0
33+ System.out.println("Record inserted successfully");
34+ else
35+ System.out.println("Record not inserted successfully");
36+
37+ }
38+
39+ }
40+ ```
You can’t perform that action at this time.
0 commit comments