/* * This sample shows how to perform an update on the student table */ // You need to import the java.sql package to use JDBC import java.sql.*; class AddStudent { public static void main (String args []) throws SQLException { if(args.length!=3){ System.out.println("Usage: java AddStudent "); System.exit(1); } int sid; String name = args[0]; String major = args[1]; int majorid=0; int gradyear=0; try { gradyear = Integer.parseInt(args[2]); } catch (NumberFormatException e){ System.out.println("Grad year must be an integer"); System.exit(1); } if(gradyear<1900 || gradyear>2100){ System.out.println("Grad year must be between 1900 and 2100"); System.exit(1); } // Get the user's name and password java.io.Console cons = System.console(); cons.printf("Enter username: "); String uname = cons.readLine(); cons.printf("Enter password: "); char[] pword = cons.readPassword(); String pwd = ""; for(char c : pword) pwd += c; try { // Connect to the database // You can put a database name after the @ sign in the connection URL. String url = "jdbc:mysql://sql.cs.oberlin.edu/studentdb?"; String parms = "user="+uname+"&password="+pwd+"&useSSL=false"; Connection conn = DriverManager.getConnection (url+parms); // Create a Statement Statement stmt = conn.createStatement (); // find the largest student id in the student table ResultSet rset = stmt.executeQuery ("select max(sid) from student"); // assign this student the max sid + 1 if (rset.next()){ sid = rset.getInt(1) + 1; } else { // if this is the first student, set the sid to 1 sid = 1; } // find the majorid for the specified major rset = stmt.executeQuery ("select did from dept"+ " where dname='"+major+"'"); // assign the majorid to this student if (rset.next()){ majorid = rset.getInt(1); } else { System.out.println("Unknown major: "+major); System.exit(1); } // Perform the update on the student table String insertStmt = "insert into student "+ "values("+sid+",'"+name+"',"+majorid+","+gradyear+")"; System.out.println(insertStmt); int x = stmt.executeUpdate(insertStmt); System.out.println(x+" student added"); // Close the Statement stmt.close(); // Close the connection conn.close(); } catch(SQLException e) { e.printStackTrace(); } catch(Exception ee){ ee.printStackTrace(); } } }