forked from Sbiswas001/Basic-java-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJDBCExample.java
More file actions
39 lines (33 loc) · 1.32 KB
/
JDBCExample.java
File metadata and controls
39 lines (33 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// JDBCExample.java
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb"; // DB name
String user = "root"; // username
String pass = "1234"; // password
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to database
Connection con = DriverManager.getConnection(url, user, pass);
System.out.println("✅ Connected to Database");
// Insert data
String insert = "INSERT INTO student (id, name) VALUES (?, ?)";
PreparedStatement ps = con.prepareStatement(insert);
ps.setInt(1, 1);
ps.setString(2, "Sayanti");
ps.executeUpdate();
System.out.println("✅ Data inserted successfully");
// Read data
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
}
// Close connection
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}