Here is the code:
PreparedStatement preparedStatement = conn.prepareStatement("update DateDeletion set DeletionDate= ? ,userName= ? where LedgerName='MiscelleniousExpenses'");
preparedStatement.setString(1,Deletiondate);
preparedStatement.setString(2,userName);
//preparedStatement.setTimestamp(3,null);
//preparedStatement.setString(4,"MiscelleniousExpenses");
System.out.println("date :"+Deletiondate+"username :"+userName+"ts :"+timeStamp);
int rowsUpdated= preparedStatement.executeUpdate();//for insert statement
System.out.println(rowsUpdated);
conn.close();
if(rowsUpdated>0){
System.out.println ("Ok.");
//ExpenditureMasterBeanInit();
return "updated";
}
rowsupdated is giving 0 rows updated.....when i check for
'select Deletiondate from Datedeletion where LedgerName='MiscelleniousExpenses';
it is giving me one value what could be wrong??
I have inserted records but did not commit. Thats why the data was not coming using JDBC in jsf page. How fool I have been.
Related
I have a section in my application which require to update two tables at the same time (WORKTR and BRTR).
However, the program only works on the first table update query while the second query did not work, resulting only a table been updated. There are no error prompt at the Log error.
Here is my jdbc code to update both table:
String query=("UPDATE WORKTR SET status = ? WHERE Pf_no = ? AND status = ? AND Scan_by= ? AND Start_date= ?");
PreparedStatement ps = con.prepareStatement(query);
// set the preparedstatement parameters
ps.setString(1,a_status);
ps.setString(2,OperatorPF);
ps.setString(3,b_status);
ps.setString(4,PIC);
ps.setString(5,dates);
// call executeUpdate to execute our sql update statement
ps.executeUpdate();
if (ps.executeUpdate()==1) {
String queryBRTR= ("Update BRTR set end_break = ?, status= ? where and PF_No= ? and work_date= ?");
PreparedStatement br = con.prepareStatement(queryBRTR);
// set the preparedstatement parameters
br.setString(1,currentTime);
br.setString(2,a_status);
// br.setString(3,b_status);
br.setString(3,OperatorPF);
br.setString(4,dates);
// call executeUpdate to execute our sql update statement
br.executeUpdate();
if( br.executeUpdate()==1){
z="You may resume your work now";
}
else{
ps.close();
br.close();
}
Please highlight if there is any mistake or suggest another way that would work to update both table.
Change to
int rowsChanged = ps.executeUpdate();
if (rowsChanged >= 1) {
You were calling executeUpdate twice.
Should not re-execute the PreparedStatement
Status has changed so even if you could re-use PreparedStatement , the update would probably fail
My code is having some error, and when I'm writing a roll number which is not present in the database and pressing the delete button then also a message pops up saying "record deleted successfully".
Actually I wanted to create a project of students report and by connecting java and MySQL. So I wrote code for the delete button, in which if the roll no of a student is written and pressed delete it will delete the record of that particular student.
so hope u understood my problem and looking forward for an accurate answer.
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/stud","root","");
Statement stmt=con.createStatement();
String query="delete from info where rollno="+rn.getText();
int d = stmt.executeUpdate(query);
JOptionPane.showMessageDialog(null,"record deleted successfully!!!");
rn.setText("");
First of all, use PreparedStatement in which you fill in the parameters instead of composing a SQL-string.
May avoid very nasty errors (How does the SQL injection from the "Bobby Tables" XKCD comic work?). So
PreparedStatement stmt = con.prepareStatement("DELETE FROM info WHERE rollno=?");
stmt.setLong(1, Long.parseLong(rn.getText()));
int d = stmt.executeUpdate();
As far as your question is concerned:
The method executeUpdate returns the number of rows affected.
If it equals 0, no rows were deleted.
if (d == 0)
{
JOptionPane.showMessageDialog(null,"This record does not exist");
// Return or thrown an exception or whatever to interrupt the operation
}
else
JOptionPane.showMessageDialog(null,"record deleted successfully!!!");
showMessageDialog should get executed only if the value of d variable is positive i.e. some records got deleted from database. e.g.
Class.forName("java.sql.DriverManager");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/stud","root","");
Statement stmt=con.createStatement();
String query="delete from info where rollno="+rn.getText();
int d = stmt.executeUpdate(query);
if(d>0){
JOptionPane.showMessageDialog(null,"record deleted successfully!!!");
}
rn.setText("");
Check if result of executeUpdate is > 0. If yes, your entry was deleted.
Enter in rn: 1 or 1=1 and enjoy. Using PreparedStatements will prevent this evil SQL injection. Also it takes care of apostrophes around SQL strings and escaping apostrophe and other chars.
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/stud","root","");
String query="delete from info where rollno=?";
try (PreparedStatement stmt = con.prepareStatement(query)) {
stmt.setLong(1, Integer.parseLong(rn.getText()));
int d = stmt.executeUpdate();
if (d != 0) {
JOptionPane.showMessageDialog(null, "Record deleted successfully.",
JOptionPane.INFORMATION_MESSAGE);
}
}
This try-with-resources will ensure that stmt is always closed
String sql = "Select MAX(ORDERLINEID) From ORDERLINESTABLE";
ResultSet rst;
rst = stmt.executeQuery(sql);
if(rst.next())
{
next = rst.getInt("ORDERLINEID");
next++;
}
I have a table called ORDERLINESTABLE in my database which is currently empty. I have run the above code with the aim is to get the highest integer stored in the ORDERLINEID column allowing me to increment it when adding items to the database.
I expected this query to return nothing as the table is empty but when debugging I noticed that the search is returning true for the rst.next() method.
Does anyone have any idea why this would be? I have looked at the resultset.next() documentation and as far as I can see it should return false.
When in doubt, look at your data. Here is a sample query from any db engine.
select max(field) maxValue
from table
where 1=3
It will yield
maxValue
Null
In other words, your query is returning one record with a value of null.
It is much better to fetch the ORDERLINEID filled in by the database after the INSERT statement. Make the column ORDERLINEID of type INT AUTOINCREMENT.
String sql = "INSERT INTO ORDERLINESTABLE(xxx, yyy) VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, xxx);
stmt.setInt(2, yyy);
int updateCount = stmt.executeUpdate(); // 1
try (ResultSet id = stmt.getGeneratedKeys()) {
if (id.next()) { // 'if' as just 1 row inserted.
int orderLineId = id.getInt(1); // 1 key per row.
}
}
}
Java has a database independent way to fetch the generated keys of an INSERT. That is a lot safer than taking the MAX afterwards or before, in a multi-user environment.
Scenarios for wrong IDs are numerous in a multiuser environment:
first SELECT
second SELECT
second increment for new ID
first increment for new ID
first INSERT
second INSERT
I have an assignment where I need to update records using a PreparedStatement. Once the record have been updated as we know update query return count, i.e., number of row affected.
However, instead of the count I want the rows that were affected by update query in response, or at least a list of id values for the rows that were affected.
This my update query.
UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;
Normally it will return count of row affected but in my case query should return the ids of row or all the row affected.
I have used the returning function of PostgreSQL it is working but is not useful for me in that case.
i have used returning function of PostgreSQL but is not useful for me
It should be. Perhaps you were just using it wrong. This code works for me:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%' RETURNING id";
try (PreparedStatement s = conn.prepareStatement(sql)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getResultSet()) {
// loop through rows from the RETURNING clause
while (rs.next()) {
System.out.println(rs.getInt("id")); // print the "id" value of the updated row
}
}
}
The documentation indicates that we can also use RETURNING * if we want the ResultSet to include the entire updated row.
Update:
As #CraigRinger suggests in his comment, the PostgreSQL JDBC driver does actually support .getGeneratedKeys() for UPDATE statements too, so this code worked for me as well:
sql = "UPDATE table1 SET customer = customer || 'X' WHERE customer LIKE 'ba%'";
try (PreparedStatement s = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
s.execute(); // perform the UPDATE
try (ResultSet rs = s.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1)); // print the "id" value of the updated row
}
}
}
Thanks, Craig!
You might be able to use JDBC's support for getting generated keys. See the Connection.prepareStatement(String sql, int[] columnIndexes) API method, then use Statement.getGeneratedKeys() to access the results.
The spec says "the driver will ignore the array if the SQL statement is not an INSERT statement" but I think PostgreSQL's JDBC driver will actually honour your request with other statement types too.
e.g.
PreparedStatement s = conn.prepareStatement(sql, new String[] {'id'})
s.executeUpdate();
ResultSet rs = s.getGeneratedKeys();
Otherwise, use RETURNING, as Gord Thompson describes.
There are two way of doing it
1. by passing an array of column name or index of column prepareStatement
i.e conn.prepareStatement(sql, new String[] {'id','uname'})
and
2. by using Statement.RETURN_GENERATED_KEYS in prepareStatement.
My code is for this i.e as per my requirement i have developed my code you can have a look for better idea.
private static final String UPDATE_USER_QUERY= "UPDATE User_Information uInfo SET address = uInfo.contact_number || uInfo.address where uInfo.user_id between ? AND ?;";
//pst = connection.prepareStatement(UPDATE_USER_QUERY,columnNames);
pst = connection.prepareStatement(UPDATE_USER_QUERY,Statement.RETURN_GENERATED_KEYS);
ResultSet rst = pst.getGeneratedKeys();
List<UserInformation> userInformationList = new ArrayList<UserInformation>();
UserInformation userInformation;
while (rst.next()){
userInformation = new UserInformation();
userInformation.setUserId(rst.getLong("user_id"));
userInformation.setUserName(rst.getString("user_name"));
userInformation.setUserLName(rst.getString("user_lName"));
userInformation.setAddress(rst.getString("address"));
userInformation.setContactNumber(rst.getLong("contact_number"));
userInformationList.add(userInformation);
}
That think i need to achieve in this case.
Hope so this will help you a lot.
I write a little program to admin my video collection.
/*
insert new data set into the table
*/
int next = 0;
rs = st.executeQuery("Select max(category_id) from category;");
if (rs.next()) {
next = rs.getInt(1) + 1;
System.out.println(next);
}
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
rs = st.executeQuery(query);
//on this place is the exception thrown
// this will not execute anymore
rs = st.executeQuery("DELETE FROM category WHERE name = 'Mystics';");
The program can select on tables, make joins but insert make trouble.
I try to insert some new data in my table (see Java-code). After the second test the output show me that the data was inserted. But after Insert was an exception thrown.
1 & 2 are the tests from yesterday and today. (3) was inserted but not selected yet.
1 Mystics 2015-07-05
2 Mystics 2015-07-06
3
org.postgresql.util.PSQLException: query produced no result.
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:287)
at postgre_java.Zetcode.main(Zetcode.java:55)
do you have some advises for me?
Do not manipulate data with read statements!
If you want to insert, update, delete data in db use
Statement stmt = conn.createStatement();
stmt.executeUpdate(SQL);
executeQuery returns resultset, but all that INSERT, UPDATE, DELETE can return is number of affected rows and that is what executeUpdate is returning.
And never, never, never*100 use string concatenation in SQL use Prepared statements!
In Java, you use executeQuery for a SELECT statement or some other statement which returns something. If you want to execute an INSERT, UPDATE or DELETE without returning something, you should use executeUpdate().
Statement#executeUpdate() is meant for that purpose
String query = "INSERT INTO category VALUES (" + next + ", 'Mystics', now());";
int noOfRows= st.executeQuery(query)
but it doesnt return a ResultSet , rather the no of rows affected that you could store into an Integer
Also your is highly vulnerable to Sql injection , try using the PreparedStatements to safeguard your code