-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSampleData.java
More file actions
74 lines (65 loc) · 2.59 KB
/
Copy pathInsertSampleData.java
File metadata and controls
74 lines (65 loc) · 2.59 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.sql.*;
public class InsertSampleData {
public static void main(String[] args) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC driver not found: " + e.getMessage());
return;
}
try {
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/", "root", "root"
);
// Create database if not exists
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS library_db");
stmt.close();
con.close();
// Now connect to the database
con = DBConnection.getConnection();
if (con == null) {
System.out.println("Database connection failed.");
return;
}
// Create table if not exists
stmt = con.createStatement();
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS books (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(50), " +
"author VARCHAR(50), " +
"issued BOOLEAN)"
);
stmt.close();
String[] books = {
"To Kill a Mockingbird|Harper Lee",
"1984|George Orwell",
"The Great Gatsby|F. Scott Fitzgerald",
"Pride and Prejudice|Jane Austen",
"The Catcher in the Rye|J.D. Salinger",
"Harry Potter and the Sorcerer's Stone|J.K. Rowling",
"The Lord of the Rings|J.R.R. Tolkien",
"The Hobbit|J.R.R. Tolkien",
"Dune|Frank Herbert",
"Neuromancer|William Gibson"
};
PreparedStatement ps = con.prepareStatement(
"INSERT INTO books(name, author, issued) VALUES(?,?,false)"
);
for (String book : books) {
String[] parts = book.split("\\|");
ps.setString(1, parts[0]);
ps.setString(2, parts[1]);
ps.executeUpdate();
System.out.println("Inserted: " + parts[0]);
}
ps.close();
con.close();
System.out.println("Sample data inserted successfully!");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}