Skip to content

Commit 066a92f

Browse files
authored
Create README.md
1 parent 8f595a9 commit 066a92f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
```

0 commit comments

Comments
 (0)