need help with a java application need to create a simple user interface on top
ID: 3822302 • Letter: N
Question
need help with a java application need to create a simple user interface on top of a relational database. The database you should use is the Java DB database. The user interface will allow a user to insert, delete, and update names from a table in the database.
The database table will look like this:
ID
FIRST_NAME
LAST_NAME
1452962065165
Rita
Red
1452962067770
Oscar
Orange
1452962070010
Yet
The ID value is generated by the application automatically. An easy way to generate this value is to use System.currentTimeMillis();. The first name (required) and last name (optional) are entered by the user.
Watch a demonstration of the application:
https://youtu.be/K6_d5Of6GxY
ID
FIRST_NAME
LAST_NAME
1452962065165
Rita
Red
1452962067770
Oscar
Orange
1452962070010
Yet
Explanation / Answer
Source Code: //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/STUDENTS"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); System.out.println("Creating table in given database..."); stmt = conn.createStatement(); String sql = "CREATE TABLE RECORD " + "(id INTEGER not NULL, " + " firstName VARCHAR(255), " + " lastName VARCHAR(255), " + " PRIMARY KEY ( id ))"; stmt.executeUpdate(sql); System.out.println("Created table in given database..."); //STEP 4: Execute a query System.out.println("Inserting records into the table..."); stmt = conn.createStatement(); String sql = "INSERT INTO Record " + "VALUES (1452962065165, 'Rita', 'Red')"; stmt.executeUpdate(sql); sql = "INSERT INTO Record " + "VALUES (1452962067770 , 'Oscar', 'Orange')"; stmt.executeUpdate(sql); sql = "INSERT INTO Record " + "VALUES (1452962070010 , 'Yet', '')"; stmt.executeUpdate(sql); System.out.println("Inserted records into the table..."); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.