Update Mysql tables upon inserting into another table - mysql

I have 2 tables, the first tables is a transactions table which has records of all transactions, and the second table is the savings table which has the total of all transactions amounts.
INSERT INTO `groupsavings`.`transactions`
(`transactions_id`, `shareholder_id`, `transactions_type`,
`transactions_date`, `amount`, `pool`)
VALUES (NULL, '1', 'credit', '2019-01-01', '100', 'poolone');
INSERT INTO `groupsavings`.`transactions`
(`transactions_id`, `shareholder_id`, `transactions_type`,
`transactions_date`, `amount`, `pool`)
VALUES (NULL, '1', 'credit', '2019-01-01', '50', 'poolone');
UPDATE `groupsavings`.`saving_pool`
SET `pool_value` = '100'
WHERE `saving_pool`.`Pool_name` = 'poolone';
UPDATE `groupsavings`.`saving_pool`
SET `pool_value` = '150'
WHERE `saving_pool`.`Pool_name` = 'poolone';
I want the savings table to cumulatively add to the savings table upon inserting into transactions table.

I guess you want to automatically update the savings table with the sum of the current amount in transaction table.
You can try this method assuming you named your database connection variables like this ( Connection con, PreparedStatement pst, ResultSet rs)
public void insertt(){
String trans_id = "";
String share_id = "";
String trans_type = "";
String trans_date = "";
String amt = "";
String poolname = "";
try{
String sql = " INSERT INTO groupsavings.transactions (transactions_id, shareholder_id, transactions_type, transactions_date, amount, pool)VALUES (?, ?, ?, ?, ?, ?)";
pst = con.prepareStatement(sql);
pst.setString(1, trans_id);
pst.setString(2, share_id);
pst.setString(3, trans_type);
pst.setString(4, trans_date);
pst.setString(5, amt);
pst.setString(6, poolname);
pst.execute();
String sql2 = "select sum(amount) from groupsavings.transactions WHERE saving_pool.pool_name = ’"+poolname+"' ";
pst = con.prepareStatement(sql2);
rs = pst.executeQuery();
int sum = 0;
while(rs.next()){
sum = rs.getInt(0);
String newpool = String.valueOf(sum);
}
String sql3 ="UPDATE groupsavings.saving_pool SET pool_value = ’"+newpool+"' WHERE saving_pool.pool_name =’"+poolname+"' ";
pst = con.prepareStatement(sql3);
pst.execute();
}
catch(SQLException e){}
}

Related

Rollback transaction not working properly

In database manipulation command such as insert, update or delete can sometime throws exception due to invalid data. To protect the integrity of application data we must make sure when we a transaction was failed we must rollback
PreparedStatement ps = null;
Connection conn = null;
try {
conn = DriverManager.getConnection( URL, USERNAME, PASSWORD );
String query = "INSERT INTO tbl1(id, username) " +
"VALUES (?, ?)";
ps = conn.prepareStatement( query );
ps.setString( 1, "javaduke" );
ps.execute();
query = "INSERT INTO tbl2 (id, tbl1_id, " +
"quantity, price) VALUES (?, ?, ?, ?)";
ps = conn.prepareStatement( query );
ps.setInt( 1, id );
ps.setInt( 2, tbl_id );
ps.setInt( 3, 10 );
ps.setDouble( 4, 29.99 );
ps.execute();
}
catch ( SQLException e )
{
conn.rollback()
e.printStackTrace();
}
I guess this is Java.
Right after you get your connection object, turn off autocommit, like so.
conn = DriverManager.getConnection( URL, USERNAME, PASSWORD );
conn.setAutoCommit(false);
Right after your last execute() do this.
conn.commit();
Then the rollback() in your exception handler should do what you expect.
This should extend the scope of your transaction to beyond a single SQL query.

How to read a data file and insert data into a mysql database

I am new to Java and I'm trying to insert data into a mysql database using a text file. My text file has 5 rows. I have 3 SQL insert Queries. Each query will insert 5 rows into the database.
Example queries are:
INSERT INTO `session` (`emp`, `SessionID`, `SessionDate`, `SessionStartTime`, 'SessionEndTime') VALUES (Tyler, NULL, ?, ?, ?);
INSERT INTO `session` (`emp`, `SessionID`, `SessionDate`, `SessionStartTime`,'SessionEndTime') VALUES (MAX, NULL, ?, ?, ?);
INSERT INTO `session` (`emp`, `SessionID`, `SessionDate`, `SessionStartTime`,'SessionEndTime') VALUES (James, NULL, ?, ?, ?);
Example text file:
textfile
Here is a snippet of my code. I having problems with figuring out how to read the text file and inserting it into the database. Note that the code only has one my queries. I'm trying to get one query to work before adding the others.
I'm looking for some advice on reading the file and the prepared statements for the date, start time, and end time.
any suggestions?
try
{
//Create a mysql database connection
String dbUrl = "jdbc:mysql://localhost:3306/mytest";
String username = "root"; //Database Username
String password = "abcdefg"; //Database Password
Class.forName("com.mysql.jdbc.Driver"); //Load mysql jdbc driver
Connection con = DriverManager.getConnection(dbUrl,username,password); //Create Connection to DB
// mysql query to insert data into session table
String query = " INSERT INTO `session` (`emp`, `SessionID`,
`SessionDate`, `SessionStartTime`) VALUES (Tyler, NULL, ?, ?, ?);
try {
BufferedReader bReader = new BufferedReader(newFileReader("c:/sessionstime"));
String line = "";
while ((line = bReader.readLine()) != null)
{
try
{
if (line != null)
{
String[] array = line.split(",");
for(String result:array)
{
// create mysql insert preparedstatement
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setDate (1, sessiondate[0]);
preparedStmt.setTime (2, sessionstarttime[1]);
preparedStmt.setTime (3, sessionendtime[2]);
preparedStmt.addBatch();
// execute the preparedstatement
preparedStmt.executeBatch();
// close database connection
con.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}

Insert values in existing record. sqlite using prepared statement

I want to insert values into an existing record using prepared statment. The value of that record is the last record inserted, I tried LAST function and MAX but it didn't seems to work, also I tried SELECT statment inside INSERT with no luck.
public static void insertCoordinates(){
java.sql.Connection c = null;
try {
String str1 = Singelton.getInstance().getTxtField1().getText();
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:timeline_DB.db");
c.setAutoCommit(false);
PreparedStatement preparedStatement = c.prepareStatement("insert into event_table(bar_length, x_bar, y_bar) values (?, ?, ?) WHERE event_title =?");
preparedStatement.setInt(1, CanvasNewTimeLine.Event_length);
preparedStatement.setInt(2, CanvasNewTimeLine.x);
preparedStatement.setInt(3, CanvasNewTimeLine.H_LINE);
preparedStatement.setString(4,str1);
preparedStatement.executeUpdate();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
System.err.println("problem");
}
System.out.println("yesssssss successfully");
}
I used update instead of insert:
public static void insertCoordinates(){
java.sql.Connection c = null;
try {
String str1 = Singelton.getInstance().getTxtField1().getText();
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:timeline_DB.db");
c.setAutoCommit(false);
String updateTableSQL = "UPDATE event_table SET bar_length = ?, x_bar=?, y_bar=? WHERE event_title = ?";
PreparedStatement preparedStatement = c.prepareStatement(updateTableSQL);
preparedStatement.setInt(1, CanvasNewTimeLine.Event_length);
preparedStatement.setInt(2, CanvasNewTimeLine.x);
preparedStatement.setInt(3, CanvasNewTimeLine.H_LINE);
preparedStatement.setString(4,str1);
// execute
preparedStatement .executeUpdate();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
System.err.println("problem");
}
System.out.println("yesssssss successfully");
}

ArrayIndexOutOfBoundsException ExecuteBatch() on PreparedStatement

I'm adding 483 objects to a database with preparedStatements and ExecuteBatch().
When I run this code, all the objects are correctly added to the database but after a while the program throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 484
at com.mysql.jdbc.StatementImpl.processMultiCountsAndKeys(StatementImpl.java:1417)
at com.mysql.jdbc.PreparedStatement.executePreparedBatchAsMultiStatement(PreparedStatement.java:1515)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1389)
at model.database.SQLCommand.insertMeasurements(SQLCommand.java:110)
at model.database.SQLCommand.addDatasetToDb(SQLCommand.java:31)
at tests.readText.main(readText.java:35)
Here is my code:
private static List<Long> insertMeasurements(List<Measurement> measurements, long did) throws SQLException {
conn.setAutoCommit(false);
List<Long> mids = new ArrayList<Long>();
String sql = "INSERT INTO doses (CPS, ground, total) VALUES (?, ?, ?);" + " " +
"INSERT INTO places (x, y, z, speed) VALUES (?, ?, ?, ?);" + " " +
"INSERT INTO measurements (time, place, note, dose, id_dataset) VALUES (?, (SELECT MAX(ID) FROM places), ?, (SELECT MAX(ID) FROM doses), ?)";
try (
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
for(Measurement measurement: measurements) {
ps.clearParameters();
double cps = measurement.getDose().getCps();
double ground = measurement.getDose().getGround();
double total = measurement.getDose().getTotal();
ps.setDouble(1, cps);
ps.setDouble(2, ground);
ps.setDouble(3, total);
double x = measurement.getPlace().getX();
double y = measurement.getPlace().getY();
double z = measurement.getPlace().getZ();
double speed = measurement.getPlace().getSpeed();
ps.setDouble(4, x);
ps.setDouble(5, y);
ps.setDouble(6, z);
ps.setDouble(7, speed);
String time = measurement.getDate().toString();
String note = measurement.getNote().toString();
ps.setString(8, time);
ps.setString(9, note);
ps.setObject(10, did);
ps.addBatch();
}
ps.executeBatch();
conn.commit();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
long id = rs.getLong(1);
mids.add(id);
}
} catch (SQLException e) {
throw new SQLException("Can't add the measurement."+e.toString()+"\n" );
}
return mids;
}

How can I add this value as a query, inside of a prepared statement?

Public void aMethod(String itemName, String theUsersName){
preparedStatement = conn.prepareStatement("INSERT INTO items (Owner_ID, Name, State) VALUES (?,?,?) ");
preparedStatement.setString(1, "(SELECT id FROM users WHERE username = ' "+theUsersName+"')");
preparedStatement.setString(2, itemName);
preparedStatement.setString(3, state);
preparedStatement.executeUpdate();
}
username table contains usernames and id's
here I'm given theUsersName and want to find the id of that username, to set the Owner_ID of the new item in Item's table = theUsername's id.
Give this a try if it does not throw an exception, (or otherwise I'll delete this)
String query = "INSERT INTO items (Owner_ID, Name, State) " +
"SELECT ID, ? AS Name, ? AS State " +
"FROM users " +
"WHERE userName = ? "
preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, itemName);
preparedStatement.setString(2, state);
preparedStatement.setString(3, theUsersName);
preparedStatement.executeUpdate();
By inserting it into the original INSERT statement:
INSERT INTO items (Owner_ID, Name, State)
VALUES (SELECT id FROM users WHERE username = ?, ?,?)
and replacing the first parameter with the actual value:
preparedStatement.setString(1, theUsersName);
You can do like this: using INSERT INTO SELECT..
INSERT INTO items (Owner_ID, Name, State)
SELECT id,?,? FROM users WHERE
username = ?
Or using subquery like this:
INSERT INTO items (Owner_ID, Name, State)
VALUES ((SELECT id FROM users WHERE username = ? LIMIT 1),?,?)
Here you have to set limit to 1.
You first have to fetch the Id from the users table then you can pass it.Have a look on :
preparedStatement = conn.prepareStatement("SELECT id FROM users WHERE username = ' "+theUsersName+"'");
ResultSet rs=preparedStatement.executeQuery();
if(rs.next())
int id=rs.getInt(1);
preparedStatement.setString(1,id);