I am creating a application using Java AND JDBC in eclipse IDE to insert user details like name
, userId
, DOB
, Address
, Phone number
, etc, taken dynamically and to store in database table and then fetch it.
For date-of-birth (DOB) and phone number fields, I have to add validation, i.e. DOB should be between 2000-01-01 and 1940-01-01 and phone number should be exactly 10 digits.
this is the query used to create table--> String q = "create table UserDetails1 (userid int(20),name varchar(100),DOB DATE, address varchar(300),phone BIGINT, UserRole varchar(20)) " ;
Any help would be appreciated.
Below is the code I have done so far
public class UserData {
public static void main(String[] args) throws Exception {
int option = 0;
do {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "root");
Scanner sc = new Scanner(System.in);
System.out.println("Select from the following options to interact with the user data :" + '\n');
System.out.println("1. Insert user data in database");
System.out.println("2. Display all users data");
System.out.println("3. Delete specific user by Userid");
System.out.println("4. Display specific user data as per their Userid");
System.out.println("5. Exit " + '\n');
option = sc.nextInt();
switch (option) {
case 1:
String y = " insert into UserDetails(userid,name,DOB,address,phone,UserRole) values(?,?,?,?,?,?)";
PreparedStatement st1 = con.prepareStatement(y);
System.out.println("Enter Userid");
int id1 = sc.nextInt();
System.out.println("Enter name");
String name1 = sc.next();
System.out.println("Enter DOB in YYYY-MM-DD format");
String dateOfBirth = sc.next();
Date date1 = Date.valueOf(dateOfBirth);
sc.nextLine();
System.out.println("Enter address ");
String address1 = sc.nextLine();
System.out.println("Enter 10 digit phone number");
double phone1 = sc.nextDouble();
System.out.println("Enter user role:");
String userrole1 = sc.next();
st1.setInt(1, id1);
st1.setString(2, name1);
st1.setDate(3, date1);
st1.setString(4, address1);
st1.setDouble(5, phone1);
st1.setString(6, userrole1);
st1.executeUpdate();
System.out.println("data inserted");
con.close();
break;
case 2:
case 3:
case 4:
case 5:
System.out.println("Exiting...." + '\n');
break;
default:
System.out.println('\n' + "Choose from the available options..! " + '\n');
}
} while (option != 5);
}
}