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
Related
I have an old database and i want to load the new data from that database every hour into a new database (That i created) using a java code..
i tested that just in two simple databases using this code but it doesn't work for me , can any of u help me or give me some ideas:
import java.sql.*;
class DB{
public static void main(String args[]) {
try {
//loading the jdbc driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/b", "root", "");
Statement stmt = con.createStatement();
//int rows = stmt.executeUpdate("INSERT INTO b.table2 SELECT * FROM a.table1");
ResultSet rs = stmt.executeQuery("INSERT INTO b.table2 SELECT * FROM a.table1");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}}
Your code as printed will work fine. INSERT statements do not return a resultset; they return a single number that represents how many rows were affected. Your commented out code is therefore correct; your uncommented line (using .executeQuery) isn't useful here and probably won't work.
see the screenshots
see the 2nd screenshot
see the 3rd screenshot
Okay so I am building a project on java and mysql, I am stuck at this point that I have to update a data which is in MySql but from my java gui application, I've executed that update command from MySql command line client
update user set bldu = 50 where userid = 1001;
and it's working perfectly fine there but from my java application on clicking on assigned jbutton it says:
you have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'userid= 1001' at line 1
Please help me..!
In your first screenshot you must add a space before WHERE clause:
String query = "UPDATE user SET bdlu = " + bldut + "WHERE userid = " + uid + ";";
So your query will be interpretated as:
UPDATE user SET bdlu = 50WHERE userid = 1001
So you'll raise a syntax error.
Then you'll have the following query:
String query = "UPDATE user SET bdlu = " + bldut + " WHERE userid = " + uid + ";";
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
use this one instead of your old query may be it is helpful for you.
Try this snippet in your code.
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
Statement = con.prepareStatement(query);
Statement.executeUpdate();
by looking at your code you cannot store results of update query in resultSet the executeUpdate() only return 0 or 1 for success and failure of Update.
Okay i guys i have figured out something that it is working i mean this program is updating the data stored in mysql from netbeans via jdbc but it won't stop showing that error message like:
"Can not issue data manipulation statements with executeQuery()"
everytime i click one that assigned jButton..! but i checked the database the value i want to change is being changed but then why it is showing this error..?
Please use this code in your java file, do changes according to your file. your issue is you are using the same query in a result set that already uses for the update
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bdb", "root", "root");
try {
String query = "update user SET bldu = " + bldut+ " WHERE userid = " + uid + ";";
// create the java mysql update preparedstatement
Class.forName("com.mysql.jdbc.Driver").newInstance();
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.executeUpdate();
query = "select * from user WHERE userid = " + uid +";";
ResultSet rs = stmt.executeQuery(query);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String userid = rs.getString("userid");
String userfname = rs.getString("userfname");
// all your column
// Display values
System.out.print("userid: " + userid);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// finally block used to close resources
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
I am trying to update a table using Java JDBC. The method I am using does not throw any errors but the table is not updating. The create table method is below:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS CUSTOMERS2 " +
"(PHONE TEXT PRIMARY KEY NOT NULL," +
" SURNAME TEXT NOT NULL, " +
" FIRSTNAME TEXT NOT NULL, " +
" HOME TEXT, " +
" ADDRESS TEXT, " +
" POSTCODE Text)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Customers2 created successfully");
}
The update method is below:
public static void updateCustomers()
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
pstmt = c.prepareStatement(query); // create a statement
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
pstmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully HELLO");
}
I have tried to find some clear instructions on this but cant find any. I do not really understand JDBC and prepared statement very well
When autoCommit is false (c.setAutoCommit(false);), you must manually commit the transaction...
Add...
c.commit()
After pstmt.executeUpdate();
You code also has a flaw, in that if some kind of error occurs during the preparation or execution of the statement, both the Connection and PreparedStatement could be left open, causing a resource leak
If you're using Java 7+ you can use the try-with-resources feature, for example...
try {
Class.forName("org.sqlite.JDBC");
try (Connection c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db")) {
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query = "UPDATE CUSTOMERS2 set ADDRESS = ? where PHONE = ? ";
try (PreparedStatement pstmt = c.prepareStatement(query)) {
pstmt.setString(1, "1"); // set input parameter 1
pstmt.setString(2, "DOES THIS WORK"); // set input parameter 2
pstmt.executeUpdate(); // execute update statement
c.commit();
}
} catch (SQLException exp) {
exp.printStackTrace();
}
} catch (ClassNotFoundException exp) {
exp.printStackTrace();
System.out.println("Failed to load driver");
}
This will ensure that regardless of how you leave the try block the resource will be closed.
You might also consider taking a look at the JDBC(TM) Database Access
Your update method will set ADDRESS to 1 if there is any row in table with PHONE = does this work.
Try to put Address in 1st Input parameter and Phone 2nd Input parameter
When a connection is created, it is in auto-commit mode.
We need to use [setAutoCommit] method only when we need to make Auto Commit false and make it manual commit after executing the query.
More details at Oracle site on JDBC Transaction.
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
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.