My program prompts the user to enter an ID and then enter a new amount for the ID they selected, when they enter a new amount it writes a new row to the database, what I want to do is when they enter that new amount I want it to delete the existing data about the user so it doesn't write the same information to the database with just a new value.
Player updatedPlayer = null;
System.out.println("Enter the player ID:");
String playerId = FileUtility.getInput().nextLine();
System.out.println("Here are the players");
//theList = loadCampersFromDatabase(theList);
for (Player camper : PlayerDAO.selectAllById(playerId)) {
System.out.println(camper);
System.out.println("Enter the new amount paid");
newAmount = FileUtility.getInput().nextInt();
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sql = "DELETE FROM Camper WHERE id = ?, INSERT INTO `Camper`(`id`, `firstName`, `lastName`, `parentsName`,`phoneNumber`,`email`,`amountPaid`) "
+ "VALUES (?,?,?,?,?,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setInt(1, camper.getRegistrationId());
preparedStatement.setString(2, camper.getFirstName());
preparedStatement.setString(3, camper.getLastName());
preparedStatement.setString(4, camper.getParentsName());
preparedStatement.setInt(5, camper.getPhoneNumber());
preparedStatement.setString(6, camper.getEmail());
preparedStatement.setInt(7, MainClass.getNewAmount());
// execute update SQL stetement
preparedStatement.executeUpdate();
System.out.println("Record is updated to DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
Related
I have an error saving the data in my database in two different tables. but with the same ID_USER however one is a primary key and the other unique.
I need that when creating the user it can automatically generate the ID_USER for the other table and save its password. How do I rescue the ID_USER from the previous table to insert it in another? since when I run it I get an error
"Cannot add or update a child row: a foreign key constraint fails (tests``private, CONSTRAINT private_ibfk_1 FOREIGN KEY (ID_USER) REFERENCES user (ID_USER) ON DELETE CASCADE ON UPDATE CASCADE)"
is this possible to do?
private void insertarActionPerformed(java.awt.event.ActionEvent evt) {
int val = 0;
String user, pass = "";
user = jTextField_user.getText().trim();
pass = jTextField_pass.getText().trim();
if (user.equals("")) {
val++;
}
if (pass.equals("")) {
val++;
}
if (val == 0) {
try {
Connection cn = Conexion.conectar();
PreparedStatement pst = cn.prepareStatement(
"Insert into user (ID_USER,USER) values (?,?)");
pst.setInt(1, 0);
pst.setString(2, user);
pst = cn.prepareStatement(
"Insert into private (ID_USER,PASSWORD) values(?,?)");
pst.setInt(1, 0);
pst.setString(2, pass);
pst.executeUpdate();
cn.close();
JOptionPane.showMessageDialog(null, "Successful registration");
} catch (Exception e) {
System.err.println("Error user" + e);
}
}
}
solved . create variable ID. and bring it with a ResultSet the LAST_INSERT_ID ()
private void insertarActionPerformed(java.awt.event.ActionEvent evt) {
int id = 0, val = 0;
String user, pass = "";
user = jTextField_user.getText().trim();
pass = jTextField_pass.getText().trim();
if (user.equals("")) {
val++;
}
if (pass.equals("")) {
val++;
}
if (val == 0) {
try {
Connection cn = Conexion.conectar();
PreparedStatement pst = cn.prepareStatement(
"Insert into user values (?,?)");
pst.setInt(1, 0);
pst.setString(2, user);
pst.executeUpdate();
ResultSet rs = pst.executeQuery("select ID_USER from user where ID_USER = LAST_INSERT_ID() ");
if (rs.next()) {
id = rs.getInt("ID_USER");
}
pst = cn.prepareStatement(
"Insert into private values(?,?)");
pst.setInt(1, id);
pst.setString(2, pass);
pst.executeUpdate();
cn.close();
JOptionPane.showMessageDialog(null, "Successful registration");
} catch (Exception e) {
System.err.println("Error user" + e);
}
}
}
CREATE TRIGGER user
BEFORE INSERT ON private
FOR EACH ROW
BEGIN
IF new.ID_USER IS NULL THEN
SET new.ID_USER = ID_USER();
END IF;
END
;;
I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}
So I want to be able to display 500 records at a time, commit and print that it has been displayed records 1 to 500 records have been committed. And than do the next 500 records and commit again until reached the maximum records which is over 20k records. I managed to get the first 500 records but I am stuck how can I commit them and in commit them and continue to get the next 500 records and so on.
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE"
+ " WHERE profile_id >= ? AND profile_id <= ?;";
try {
dbConnection = getInformixConnection(); //connects to ICORE database
System.out.println("I am in the try");
//Gets the max profile_id record
statement = dbConnection.createStatement();
ResultSet r = statement.executeQuery("SELECT max(profile_id) AS rowcount FROM COS_PROFILE");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("COS_PROFILE table before update has " + maxCount + " row(s).");
preparedStatement = dbConnection.prepareStatement(selectTableSQL);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, maxCount);
// execute select SQL statement
rs = preparedStatement.executeQuery();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database ICORE Connection is closed");
}
}
}
private static void updateRecordIntoBids() throws SQLException {
System.out.println("I am inside update method");
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
dbConnection = getOracleConnection(); //connects to BIDS database
String updateTableSQL =
"UPDATE traffic_profile_temp SET pe_ingress_flag = ?, "
+ " pe_egress_flag = ?,"
+ " ce_ingress_flag = ?,"
+ " ce_egress_flag = ? "
+ " WHERE traffic_profile_id = ? ";
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
try {
int rowCount = 0;
while (rs.next() && rowCount < 500) {
// System.out.println("inside the while loop");
String ingressflag = rs.getString("ingress_flag"); //BIDS column is pe_ingress_flag
String egressflag = rs.getString("egress_flag"); //BIDS column is pe_egress_flag
String ceingressflag = rs.getString("ce_ingress_flag"); //BIDS column is ce_ingress_flag
String ceegressflag = rs.getString("ce_egress_flag"); //BIDS column is ce_egress_flag
int profileid = rs.getInt("profile_id"); //BIDS column is traffic_profile_id
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setInt(5, profileid);
// System.out.println(updateTableSQL);
System.out.println("Record " +profileid +" is updated to traffic_profile_temp table!");
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
System.out.println(rowCount);
}
preparedStatement.executeBatch();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database BIDS Connection is closed");
}
}
}
update this part
while (rs.next() && rowCount < 500) {
with
while (rs.next()) {
and
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
System.out.println(rowCount);
with
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
if(rowCount % 500 == 0){
preparedStatement.executeBatch();
}
System.out.println(rowCount);
This check if the rowCount can be divided by 500, execute the batch. Don't forget to execute the batch after all statements finish to execute the remaining batches which couldn't divided by 500 . for more details regarding batches
See the control after the prepared statement going to the else if(more){} block
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
int k = pst.executeUpdate();
boolean more;
if(k > 0)
{
//boolean more = rs.next();
more = true;
}
else {
more = false;
}
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
String firstName = rs.getString("name");
String lastName = rs.getString("rollnumber");
System.out.println("Welcome " + firstName); `control coming here`
ex.setFirstName(firstName);
ex.setLastName(lastName);
ex.setValid(true);
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
The main problem is the use of int k = pst.executeUpdate();
Your query isn't an update statement, so it doesn't make sense to execute an update, it is likely that this will ALWAYS return 0, as no rows where updated.
Instead use executeQuery, which returns a ResultSet, which can use to determine if there are any rows matching your query, for example
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url,user,passsword)) {
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
try (ResultSet rs = pst.executeQuery()) {
if (rs.hasNext()) {
// Registered
} else {
// Unregistered
}
}
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
You may want to take a closer look at the JDBC(TM) Database Access trail
I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;