Java web application DAO writing authenticated UserID and IP Address to DB - java

I'd like to write to my Oracle DB the user ID and IP address of the logged in user (web app) whenever I perform SQL UPDATEs and INSERTs. Such as
public static int updateUser(STKUser user, STKUser loggedIn) throws DAOException {
Connection connection = null;
connection = DB.getConnFromCache();
PreparedStatement ps = null;
String query = "INSERT INTO xtblPersonnel (pID, pPssWrd, pAdminDate, pAdminIP, pAdminBy) VALUES (?,?,SYSDATE,?,?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, user.getBadge());
ps.setString(2, user.getPassword());
ps.setString(3, loggedIn.getIpAddress());
ps.setString(4, loggedIn.getBadge());
return ps.executeUpdate();
}
catch (Exception e) {
System.out.println("SQL Exception inserting new user with badge: " + user.getBadge() + ". Error Message: " + e.getMessage());
LOGGER.log(Level.INFO, "SQL Exception inserting new user with badge: " + user.getBadge() + ". Error Message: " + e.getMessage(), user);
throw new DAOException("SQL Exception inserting new user!");
// return 0;
}
finally {
DB.closePreparedStatement(ps);
DB.releaseConnToCache(connection);
}
}
STKuser is a Javabean
My application uses a general Oracle db username and password so that is the reason why I want to record who did the update or insert and from which machine.
Is this an acceptable approach. I used to pass in the session but have realized this is a no no.

Assuming that you're properly closing all DB resources as Connection, Statement and ResultSet in the finally block of the try block where you acquired them and the code is doing what it should do, I don't forsee problems with the approach in question. There is no risk for SQL injections since you're using PreparedStatement, if that was your actual concern. Declaring the method static is however a bit a smell, but then we need to know more about the context the code is running in.

Related

Update statement working in SQLite Browser not in java with the exact same syntax

Okay I executed the same code thats in the update query in the SQLite db browser and it worked successfully
public void StatusUpdate(ActionEvent event) {
try {
String test = null;
test = txtEditStatus.getText();
System.out.println(test);
String query = "UPDATE member SET desc = ? WHERE username = ?";
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setString (1, test);
preparedStmt.setString(2, "Custom Hue");
// execute the java preparedstatement
preparedStmt.executeUpdate();
connection.close();
} catch (Exception e) {
}
However when running eclipse with JFx, it prints what I type in the console but doesnt update in the db, anyone know why?
For the user asking about the connection:
Connection connection;
public ProfileController() {
connection = SQLConnection.Connector();
if (connection == null)
System.exit(1);
}
I would check that your connection is actually connected to the correct database.
are you sure you have the right connection string set up?
you should do an output on your exception handler, what if there is an exception?
are you sure the connection is open?
are you sure the user exists in the database and table you are trying to update?
try doing a read first, to see if you have an open connection. Print your exception, just in case, never leave it blank. That's just bad practice.
How about you try a
preparedStmt.executeUpdate();
connection.commit();
connection.close();
Just incase autocommit isn't enabled?

Able to insert data but unable to update

I'm writing a Web app and using Excel as backend as i'm not supposed to use anyother. Here in my code i am performing a jdbc on 2 tables. Insert in 1 and Update in another. And below is my code.
public class PostDataDAO {
DBConnection dbConnection = new DBConnection();
public void save(UserBean postBean) throws SQLException {
String userName = new com.sun.security.auth.module.NTSystem().getName();
System.out.println(userName);
Connection conn, conn1 = dbConnection.conn;
PreparedStatement ps, ps1 = dbConnection.ps;
String excelPath = "D:\\Danny\\Result1.xls";
String mainPath = dbConnection.excelPath;
try {
dbConnection.createClassForName();
conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + excelPath + "; READONLY=FALSE;");
System.out.println("Connecting to database…");
System.out.println("Oracle JDBC Driver Registered!");
if (conn != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
String insert = "insert into [result$] VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
System.out.println(postBean.getStartDate() + " from Bean" + " end date is " + postBean.getEndDate());
ps = conn.prepareStatement(insert);
ps.setString(1, postBean.getCaseNumber());
ps.setString(2, postBean.getCaseOwner());
ps.setString(3, postBean.getStatus());
ps.setString(4, postBean.getIssue());
ps.setString(5, postBean.getReason());
ps.setString(6, postBean.getDateOpened());
ps.setInt(7, postBean.getAge());
ps.setString(8, postBean.getResolution());
ps.setString(9, postBean.getFinalStatus());
ps.setString(10, postBean.getStartDate());
ps.setString(11, postBean.getEndDate());
ps.setDouble(12, postBean.getTotalTimeTaken());
System.out.println("Date from post bean ----------------- Case Number is " + postBean.getCaseNumber());
System.out.println("Storing Object is Done!");
ps.execute();
conn1 = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + mainPath + "; READONLY=FALSE;");
System.out.println("Connecting to database…");
System.out.println("Oracle JDBC Driver Registered!");
if (conn1 != null) {
System.out.println("You made it, take control your database now! in the second block");
} else {
}
System.out.println("for m second block " + postBean.getCaseNumber());
String x = postBean.getCaseNumber();
String updateSheet = "UPDATE [report1448039568905$] SET STATE = 1 where [Case Number] = '" + x + "'";
ps1 = conn1.prepareStatement(updateSheet);
System.out.println(" and " + updateSheet);
ps1.execute();
ps1.close();
conn1.commit();
conn1.close();
ps.close();
conn.commit();
conn.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
Here my problem is, when i hit submit, the insert part is getting correctly posted. But the update part is a bit tricky and confusing.
The System.out.println() is printing everything as expected, and to post the data I'm going to my code, delete a line, undo a delete, Save it. and i get the below message in my eclipse console.
Dec 01, 2015 7:18:23 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/SFDCTracker] has started
Dec 01, 2015 7:18:24 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/SFDCTracker] is completed
Once i get the above message, the other sheet is getting updated.
What i'm confused is, why am i doing this for the second table but not for the first. The first is getting inserted without any issues.
Please let me know how can i fix this.
Here when i did some research on this, i came to know that, I'm getting data from a excel sheet and i need to update the same Cell. Initially i thought that it might be a because it might be in read only, But i didn't get any exception.
And my second conclusion is that i need to rebuild. The data gets saved upon a new build. does this mean that that the excel file is released in mean while updating and when i hit run, it gets locked again? if so how can i fix this.
Thanks

Update to MySQL returns 1, no errors/exception, but no updates actually take place

The below method is supposed to update MySql DB with the company info passed to it.
I have other methods that insert and delete and work fine, however this method runs without exceptions, and always returns 1.
The general_log file shows that it received the update string but there are still no changes.
The only time I can get it to work is if I run the code in the MySql workplace directly.
If you need more info to figure this out, please let me know.
I gave you all I thought was needed.
Thanks.
// SQL update string received from the program in the log file
// UPDATE couponsprojectdb.company SET Email = 'admin#MyCompany.org', Password = 'pass' WHERE ID = 3
public void updateCompanyById(Company c, long id) throws SQLException
{
Connection conn = pool.getConnection(); // Gets an available connection from pool
// Prepared statement string
String sql = ("UPDATE company SET Email = ?, Password = ? WHERE ID = ?");
PreparedStatement p = conn.prepareStatement(sql);
p.setString(1, c.getEmail());
p.setString(2, c.getPassword());
p.setLong(3, id);
int i = p.executeUpdate();
System.out.println("changes: " + i);
pool.releaseConnection(conn);
}
You never called conn.commit() after doing the executeUpdate(). The reason the Java code returns 1 is because it succeeded, but the database rolled back the UPDATE immediately after the transaction ended.
You also need to close your connections. Change your code to this:
try {
Connection conn = pool.getConnection();
String sql = ("UPDATE company SET Email = ?, Password = ? WHERE ID = ?");
PreparedStatement p = conn.prepareStatement(sql);
p.setString(1, c.getEmail());
p.setString(2, c.getPassword());
p.setLong(3, id);
int i = p.executeUpdate();
conn.commit(); // <-- MAKE SURE TO COMMIT THE TRANSACTION TO THE DATABASE!!!
System.out.println("changes: " + i);
pool.releaseConnection(conn);
} catch(Exception e) {
// handle errors here
} finally {
try { if (p != null) p.close(); } catch (Exception e) {};
try { if (conn != null) pool.releaseConnection(conn); } catch (Exception e) {};
}
Big hat tip to this SO post which got me thinking about your problem.

SQLite Database locking up on Delete Command

I have a problem where I can't seem to get this simple delete command working. Everytime I run it it just locks the database and crashes
The id parameter exists in the database
the database is small. Only a few tables.
update commands work completely fine.
The id is an in and resulting command is - DELETE from Employees where ID = 2;
public static void EmployeeDeleteByID(int idIn){
Connection c = null;
Statement stmt = null;
try {
c = Connect();
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "DELETE from Employees where ID = " + idIn + ";";
System.out.println(sql);
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println("Error 1 : " + e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
Error after running : java.sql.SQLException: database is locked
"database is locked" means that some other connection still has an active transaction.
If there is no other process accessing the database, you have to check all connections in your program; at least one of them forgot a commit().
The code actually works fine.
It turned out another method was being called to fill a JCombo which was keeping a connection open due to an error being caused by calling a null value from database.
It wasnt obvious as there was no code in the exception box.
Silly little problem so people always make an error throw some kind of stack trace or warning.
Thanks

Checking if user exists in Oracle Database - java jdbc

So I have this working code/prepared statement that adds a username and password into a database, however I need to check if the username already exists in the code.
public void addUser(Connection conn, PreparedStatement pstmnt, String username, String password)
{
try
{
pstmnt = conn.prepareStatement("insert into users values (?,?,?)");
pstmnt.setInt(1, 0);
pstmnt.setString(2, username);
pstmnt.setString(3, password);
pstmnt.executeUpdate();
}
catch (SQLException e) { System.out.println("Error: " + e.getMessage()); }
System.out.println(username + " has been added");
}
Is there any simple way to do this?
You can add a unique constraint in the DB and handle the exception in addUSer accordingly
If there's no many duplicate key risk, you can just try and check the error code if it matches "dup key error" (Error ORA-00001).
Else you must lock the entire table, check for key existence, update and then commit (which release the lock)

Categories

Resources