package
jdbcDemo;
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.SQLException;
import
java.sql.Statement;
import
java.util.Scanner;
public
class
GfGJdbcDemo {
public
static
void
main(String[] args)
throws
SQLException {
String username =
"root"
;
String password =
""
;
try
(Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement()) {
Scanner scanner =
new
Scanner(System.in);
int
choice;
do
{
System.out.println(
"\nOptions:"
);
System.out.println(
"1. Create table"
);
System.out.println(
"2. Insert data"
);
System.out.println(
"3. Update data"
);
System.out.println(
"4. Delete data"
);
System.out.println(
"5. Add column"
);
System.out.println(
"6. Drop column"
);
System.out.println(
"0. Exit"
);
System.out.print(
"Enter your choice: "
);
choice = scanner.nextInt();
switch
(choice) {
case
1
:
createTable(statement);
break
;
case
2
:
insertData(statement);
break
;
case
3
:
updateData(statement);
break
;
case
4
:
deleteData(statement);
break
;
case
5
:
addColumn(statement);
break
;
case
6
:
dropColumn(statement);
break
;
case
0
:
System.out.println(
"Exiting program."
);
break
;
default
:
System.out.println(
"Invalid choice. Please enter a valid option."
);
}
}
while
(choice !=
0
);
}
catch
(SQLException e) {
e.printStackTrace();
}
}
private
static
void
createTable(Statement statement)
throws
SQLException {
String createTableSQL =
"CREATE TABLE IF NOT EXISTS users ("
+
"id INT AUTO_INCREMENT PRIMARY KEY,"
+
"username VARCHAR(50) NOT NULL,"
+
"email VARCHAR(100) NOT NULL)"
;
statement.executeUpdate(createTableSQL);
System.out.println(
"Table created successfully."
);
}
private
static
void
insertData(Statement statement)
throws
SQLException {
String insertSQL =
"INSERT INTO users (username, email) VALUES ('john', 'john@example.com')"
;
statement.executeUpdate(insertSQL);
System.out.println(
"Data inserted successfully."
);
}
private
static
void
updateData(Statement statement)
throws
SQLException {
String updateSQL =
"UPDATE users SET email = 'newemail@example.com' WHERE username = 'john'"
;
statement.executeUpdate(updateSQL);
System.out.println(
"Data updated successfully."
);
}
private
static
void
deleteData(Statement statement)
throws
SQLException {
String deleteSQL =
"DELETE FROM users WHERE username = 'john'"
;
statement.executeUpdate(deleteSQL);
System.out.println(
"Data deleted successfully."
);
}
private
static
void
addColumn(Statement statement)
throws
SQLException {
String addColumnSQL =
"ALTER TABLE users ADD COLUMN age INT"
;
statement.executeUpdate(addColumnSQL);
System.out.println(
"Column added successfully."
);
}
private
static
void
dropColumn(Statement statement)
throws
SQLException {
String dropColumnSQL =
"ALTER TABLE users DROP COLUMN age"
;
statement.executeUpdate(dropColumnSQL);
System.out.println(
"Column dropped successfully."
);
}
}