Why SQL UPDATE actually performs a DELETE instead? - java

I have the following code and when it executes on the record being UPDATED, the record actually ends up being DELETED from the database table. This is an Oracle Database. Very odd. So far, I have been unable to pull any logging information from the database server that might explain what is happening on a lower level. The System.out.println statements that I included show the output that I am expecting at the moment they execute, yet, when I search for the record both via the java application itself, and then later via the SQL Developer tool - looking at the table itself, the actual data is gone. This is the java code that I have. Any thoughts, ideas, or answers as to how and why an update would perform a delete, instead of just an update is appreciated, thanks. Please let me know if there is anything else you might need that I have not properly provided, thanks.
Class.forName("oracle.jdbc.driver.OracleDriver");
.
.
.
if(PBupdate.equals("updaterecords")) {
try {
ArrayList resultsArray = (ArrayList) session.getAttribute("searchresults");
int pos = 0;
String ID = "";
System.out.println("updatestaff : pos = " + pos + " resultsArray.size() = " + resultsArray.size());
while (pos < resultsArray.size()) {
System.out.println("updatestaff : pos = " + pos);
System.out.println("updatestaff : resultsArray.get(pos + 1) = " + resultsArray.get(pos + 1));
ID = "" + resultsArray.get(pos + 0) + "";
Last_Name = "" + resultsArray.get(pos + 1) + "";
First_Name = "" + resultsArray.get(pos + 2) + "";
Middle = "" + resultsArray.get(pos + 3) + "";
Phone = "" + resultsArray.get(pos + 4) + "";
Dept_Code = "" + resultsArray.get(pos + 5) + "";
Email = "" + resultsArray.get(pos + 6) + "";
Title = "" + resultsArray.get(pos + 7) + "";
Fax_Code = "" + resultsArray.get(pos + 8) + "";
Loc_Code = "" + resultsArray.get(pos + 9) + "";
System.out.println("updatestaff : ID = " + ID);
System.out.println("updatestaff : Last_Name = " + Last_Name);
System.out.println("updatestaff : First_Name = " + First_Name);
System.out.println("updatestaff : Middle = " + Middle);
System.out.println("updatestaff : Phone = " + Phone);
System.out.println("updatestaff : Dept_Code = " + Dept_Code);
System.out.println("updatestaff : Email = " + Email);
System.out.println("updatestaff : Title = " + Title);
System.out.println("updatestaff : Fax_Code = " + Fax_Code);
System.out.println("updatestaff : Loc_Code = " + Loc_Code);
stmt = conn.prepareStatement("UPDATE STAFFDIR SET Last_Name = ?, First_Name = ?, Middle = ?, Phone = ?, Dept_Code = ?, Email = ?, Title = ?, Fax_Code = ?, Loc_Code = ? WHERE ID = ?");
stmt.setString(1, Last_Name);
stmt.setString(2, First_Name);
stmt.setString(3, Middle);
stmt.setString(4, Phone);
Integer DC = Integer.valueOf(Dept_Code);
System.out.println("updatestaff: Dept_Code = " + Dept_Code);
stmt.setInt(5, DC);
stmt.setString(6, Email);
stmt.setString(7, Title);
if ((Fax_Code == null) || (Fax_Code.equals("")) || (Fax_Code.equals("null"))) {
Fax_Code = "999";
}
System.out.println("updatestaff: Fax_Code = " + Fax_Code);
Integer FC = Integer.valueOf(Fax_Code);
stmt.setInt(8, FC);
Integer LC = Integer.valueOf(Loc_Code);
System.out.println("updatestaff: Loc_Code = " + Loc_Code);
stmt.setInt(9, LC);
stmt.setString(10, ID);
int rc = stmt.executeUpdate();
System.out.println("update : rc = " + rc);
SQLWarning warning = conn.getWarnings();
while (warning != null)
{
System.out.println(warning.getMessage());
warning = warning.getNextWarning();
}
pos = pos + 14;
}
response.sendRedirect(response.encodeRedirectURL("/phonebk/updatestaff.jsp"));
} // End of try

Related

Execute java code inside java program using Nashorn

I have written a java code which will fetch the data from the table and show the output. This is basically a script that I want to run through Nashorn.
Below is the code I'm trying
public static void main(String args[]) throws ScriptException{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String script3 = "count = 0; "
+ "keyList = new java.util.ArrayList; "
+ "valueList = new java.util.ArrayList;"
+ "keyList.add('username'); "
+ "keyList.add('password'); "
+ "valueList.add('admin'); "
+ "valueList.add('admin');"
+ "java.lang.System.out.println('keyList :: ' + keyList); "
+ "java.lang.System.out.println('KeyValue :: ' + valueList);"
+ "sql = \" select * from credentials where 'isActive'='1'\";"
+ "java.lang.System.out.println('keyList.size() :: ' + keyList.size());"
+ "for (i = 0; i < keyList.size(); i++){"
+ " sql += and \\' + keyList.get(i) + \\' = \\' + valueList.get(i) + \\';}"
+ "java.lang.System.out.println('Search SQL : ' + sql); "
+ "con = GetConnected.connectToDatabase('my_db');"
+ "ps = con.prepareStatement(sql); "
+ "ps.setString(1, \"1\");"
+ "rs = ps.executeQuery(); "
+ "if (rs.isBeforeFirst()) {"
+ " count=1; "
+ " java.lang.System.out.println('Data is present in database'); "
+ "}"
+ "else "
+ " java.lang.System.out.println('Data is not present in database'); "
+ " rs.close(); " + " st.close(); " + " con.close(); ";
engine.eval(script3);
}
The error I'm getting is
Exception in thread "main" javax.script.ScriptException: <eval>:1:904 Missing close quote
count = 0; keyList = new java.util.ArrayList; valueList = new java.util.ArrayList;keyList.add('username'); keyList.add('password'); valueList.add('admin'); valueList.add('admin');java.lang.System.out.println('keyList :: ' + keyList); java.lang.System.out.println('KeyValue :: ' + valueList);sql = " select * from credentials where 'isActive'='1'";java.lang.System.out.println('keyList.size() :: ' + keyList.size());for (i = 0; i < keyList.size(); i++){ sql += and \' + keyList.get(i) + \' = \' + valueList.get(i) + \';}java.lang.System.out.println('Search SQL : ' + sql); con = GetConnected.connectToDatabase('my_db');ps = con.prepareStatement(sql); ps.setString(1, "1");rs = ps.executeQuery(); if (rs.isBeforeFirst()) { count=1; java.lang.System.out.println('Data is present in database'); }else java.lang.System.out.println('Data is not present in database'); rs.close(); st.close(); con.close();
^ in <eval> at line number 1 at column number 904
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:534)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:521)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at com.engine.nashorn.Test.main(Test.java:87)
Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:904 Missing close quote
count = 0; keyList = new java.util.ArrayList; valueList = new java.util.ArrayList;keyList.add('username'); keyList.add('password'); valueList.add('admin'); valueList.add('admin');java.lang.System.out.println('keyList :: ' + keyList); java.lang.System.out.println('KeyValue :: ' + valueList);sql = " select * from credentials where 'isActive'='1'";java.lang.System.out.println('keyList.size() :: ' + keyList.size());for (i = 0; i < keyList.size(); i++){ sql += and \' + keyList.get(i) + \' = \' + valueList.get(i) + \';}java.lang.System.out.println('Search SQL : ' + sql); con = GetConnected.connectToDatabase('my_db');ps = con.prepareStatement(sql); ps.setString(1, "1");rs = ps.executeQuery(); if (rs.isBeforeFirst()) { count=1; java.lang.System.out.println('Data is present in database'); }else java.lang.System.out.println('Data is not present in database'); rs.close(); st.close(); con.close();
^
at jdk.nashorn.internal.parser.Lexer.error(Lexer.java:1706)
at jdk.nashorn.internal.parser.Lexer.scanString(Lexer.java:988)
at jdk.nashorn.internal.parser.Lexer.lexify(Lexer.java:1615)
at jdk.nashorn.internal.parser.AbstractParser.getToken(AbstractParser.java:132)
at jdk.nashorn.internal.parser.AbstractParser.nextToken(AbstractParser.java:211)
at jdk.nashorn.internal.parser.AbstractParser.nextOrEOL(AbstractParser.java:170)
at jdk.nashorn.internal.parser.AbstractParser.next(AbstractParser.java:157)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:281)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:249)
at jdk.nashorn.internal.runtime.Context.compile(Context.java:1286)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:1253)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:625)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:532)
... 5 more
I think the place where the keyList and valueList value added to sql query it is giving problem.
sql += and \\' + keyList.get(i) + \\' = \\' + valueList.get(i) + \\';}"
that + will keep on adding until end of the script.

Java - Unknown column in 'field list' jdbc error

I've got this error from my jdbc driver. I don't know why, tho.
Here's the corresponding code:
try {
String colNames = " ";
for (int i=0; i<cols.size(); i++) {
if (i == cols.size()-1) {
colNames += cols.get(i);
} else if (i<cols.size()) {
colNames += cols.get(i)+", ";
}
}
String colValues = " ";
for (int i=0; i<values.size(); i++) {
if (i == values.size()-1) {
colValues += values.get(i);
} else if (i<values.size()) {
colValues += values.get(i) + ", ";
}
}
System.out.println(
"INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") "
);
//System.out.println(kerdojel);
PreparedStatement pst = connHandler.conn.prepareStatement
("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");
pst.executeUpdate();
pst.close();
}
"values" and "cols" are ArrayLists that contains the data from the JTable.
cols are the Column names and values are the cell values.
The output for the Sysout:
INSERT INTO `TableOne` ( nev, kor, lakhely) VALUES ( asd, 1, asd)
The error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'asd' in 'field list'
That is not how the PreaparedStatement was intended to be used. When you use a PreparedStatement, you can specify the values by using one of the "set" methods.
Here is an example:
String colNames = " ";
String colValues = " ";
for (int i=0; i<cols.size(); i++) {
if(i!=0){
colNames += ", ";
colValues += ", ";
}
colNames += cols.get(i);
colValues += "?";
}
try (PreparedStatement pst = connHandler.conn.prepareStatement("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");){
for (int i = 0; i < values.size(); i++) {
pst.setString(i+1,values.get(i));
}
pst.executeUpdate();
}
You should use the appropriate "set" method based on the column's data type (setInt(...), setDate(...), etc.). You can find more details here
Try to use command like these one to check problem existed.
PREPARE mycmd FROM 'INSERT INTO TableOne(nev,kor) VALUES (?, ?)'

This code always give an error of duplicate insertion - How to solve that?

I am trying to create an insertion in some tables with random data but i have a problem with the duplicates.
I wrote an insertion of random records in postgresql b but it returns duplicates detection and there should be no duplicates i am using every name for exactly 2680 times and the names are 22 for 58960 records total of table play_in please check and tell what's wrong with it and how does produce a duplicate.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Random;
public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
int year;
int year1;
int num_rating;
int num_ratingAvg;
String[] round = new String[5];
round[0] = "32nd";
round[1] = "16th";
round[2] = "quarter_final";
round[3] = "SemiFinal";
round[4] = "FInal";
String[] name1 = new String[22];
name1[0] = "ahmed";
name1[1] = "mohamed";
name1[2] = "mai";
name1[3] = "salma";
name1[4] = "walid";
name1[5] = "wael";
name1[6] = "fadwa";
name1[7] = "nada";
name1[8] = "nahla";
name1[9] = "mustafa";
name1[10] = "ola";
name1[11] = "omar";
name1[12] = "amr";
name1[13] = "beshoy";
name1[14] = "marina";
name1[15] = "gerges";
name1[16] = "botros";
name1[17] = "mina";
name1[18] = "menna";
name1[19] = "feasal";
name1[20] = "youssef";
name1[21] = "moussa";
Random id = new Random();
Random roundc = new Random();
String round1;
int idc;
String name;
Random namec = new Random();
int namecounter = 0;
Random belle = new Random();
int belec = 0;
Random yearc = new Random();
Random num_ratingsc = new Random();
int num_ratingSum = 0;
// roundc.nextInt(4);
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/a2", "mohamed", "1234");
System.out.println("Opened database successfully");
String sql3;
String sql4;
stmt = c.createStatement();
String sql = "CREATE TABLE cup_matches "
+ "(MID INT PRIMARY KEY NOT NULL,"
+ " ROUND TEXT NOT NULL, "
+ " YEAR INT NOT NULL, "
+ " NUM_RATINGS INT NOT NULL, "
+ " RATING INT NOT NULL)";
String sql1 = "CREATE TABLE played_in "
+ "(MID INT NOT NULL,"
+ " NAME TEXT NOT NULL, "
+ " YEAR INT NOT NULL, "
+ " POSITION INT NOT NULL, "
+ "CONSTRAINT pk_played_in PRIMARY KEY (MID, NAME));";
String sql2 = "ALTER TABLE played_in ADD CONSTRAINT ref FOREIGN KEY (MID) REFERENCES cup_matches (MID);";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
for (int i = 0; i < 2680; i++) {
year = yearc.nextInt(2014 - 1900) + 1900;
num_rating = num_ratingsc.nextInt(1000);
num_ratingSum += num_rating;
num_ratingAvg = num_ratingSum / (i + 1);
round1 = "\'" + round[roundc.nextInt(4)] + "\'";
sql3 = "INSERT INTO cup_matches (MID, ROUND, YEAR, NUM_RATINGS, RATING) "
+ "VALUES ("
+ i
+ ", "
+ round1
+ ", "
+ year
+ ", "
+ num_rating + ", " + num_ratingAvg + ");";
stmt.executeUpdate(sql3);
System.out.println(sql3);
}
for (int j = 0; j < 58960; j++) {
idc = j;
idc = (idc >= 2679) ? 0 : idc;
year1 = yearc.nextInt(2014 - 1900) + 1900;
num_rating = num_ratingsc.nextInt(1000);
if ((belle.nextInt(2 - 1) + 1) == 1 && belec < 118) {
name = "\'" + name1[namecounter] + "belle" + "\'";
sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) "
+ "VALUES (" + idc + ", " + name + ", " + year1
+ ", " + num_rating + ");";
stmt.executeUpdate(sql4);
belec++;
idc++;
System.out.println(idc + " " + namecounter);
namecounter++;
} else {
name = "\'" + name1[namecounter] + "\'";
sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) "
+ "VALUES (" + idc + ", " + name + ", " + year1
+ ", " + num_rating + ");";
stmt.executeUpdate(sql4);
namecounter++;
idc++;
System.out.println(idc + " " + namecounter);
}
namecounter = (namecounter < 22) ? namecounter : 0;
}
// stmt.executeUpdate(sql);
// stmt.executeUpdate();
// stmt.executeUpdate(sql2);
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Table created successfully");
}
}
This line:
idc = (idc >= 2679) ? 0 : idc;
is causing you problems as you later use idc as the value for mid, which is your primary key. This line returns 0 when idc is >= 2679, which will give you duplicate key errors.
This line makes idc = 0 for each j value above 2679.
idc = j;
idc = (idc >= 2679) ? 0 : idc;
The first time, it will insert in the table played_in with idc = 0 and will insert that value for each name, when the name counter starts again with 0:
namecounter = (namecounter < 22) ? namecounter : 0;
It will try to insert the first name with 0 again and it will fail due to duplicate key error

Having Syntax Error in code java

Why is there a syntax error in this code?
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num + ","
+ "Email = '" + email_add + "',"
+ "Address = '" + mail_add + "',"
+ "SurveyStatus = " + radio_group + ","
+ "Subscription = " + receive_info +
"WHERE membership_ID = '" + member_ID';
I thought my code was right.
If it is the error in your code, check all the variables that you have used are declared and initialized with proper values.
If it is the syntax of the sql that is bothering you , here is what your sql would look like if all the variables are initialized to null.
UPDATE Customers SET (Contact)null,Emailnull,Address,null,SurveyStatus,null,SubscriptionnullWHERE MembershipID =null
Use spaces in your strSqlUpdate to correct the above sql.
EDIT
What you need is something like this.
String strSqlUpdate = "UPDATE Customers SET Contact = " + contact_num
+ ",Email = '" + email_add + "'"
+ ",Address = '" + mail_add + "'"
+ ",SurveyStatus = '" + radio_group + "'"
+ ",Subscription = '" + receive_info + "' "
+ "WHERE membership_ID = '" + member_ID + "'";
I get no syntax errors when I declare and Initialize all of the variables. You have to make sure they're all initialized, within the scope of the strSqlUpdate
String contact_num = "";
String email_add = "";
String mail_add = "";
String radio_group = "";
String receive_info = "";
String member_ID = "";
String strSqlUpdate = " UPDATE Customers SET (Contact)" + contact_num + "," + "Email"
+ email_add + "," + "Address" + "," + mail_add + "," + "SurveyStatus" + "," + radio_group
+ "," + "Subscription" + receive_info + "WHERE MembershipID =" + member_ID;
Also considering you're talking about SQL syntax, adding on to what others have said, I'd advise you should use a PreparedStatement to avoid SQL injection.
PreparedStatement pst = conn.prepareStatement(
"UPDATE Customers SET (Contact) ?, ?, ?, ?, ?, ?, ? WHERE ? = ?");
pst.setString(1, contact_num);
pst.setString(2, email_add);
... and so on
An error in your current SQL syntax is this
"Subscription" + receive_info + "WHERE MembershipID
Translated as
"...Subscrptionreceive_infoWHERE MembershipID..."
You need to add spaces wherever you don't have commas

JAVA + Mysql PreparedStatement.setString() ArrayStoreException

I've been getting this ArrayStoreException in my code for loading records from one mysql table to another. I tried truncating the destination table and running my code again and it seems that it encounters the said exception randomly.
I was going to implement a (Spring) JdbcTemplate based DAO when i've encountered an ArrayStoreException during unit testing. I tried to recreate it with ordinary JDBC code and still encounter the error.
For my DDL:
All the columns are of type varchar, except for brthdate and birthdate which are of type Date. DEFAULT CHARSET=utf8
My code snippet:
employeesSql = "select id_no, " +
"lastname, " +
"frstname, " +
"mdlename, " +
"brthdate,sex, " +
"sss_no, " +
"tin_no " +
"from lms.pms_empf " +
"where length(trim(id_no)) > 0 " +
"and id_no <> '000000' " +
" ORDER BY id_no";
employeeSql = "select count(*) "
+ "from dim_employees "
+ "where id_no=?";
updateSql = "update dim_employees " +
"set last_name = ?, " +
"first_name = ?, " +
"middle_name = ?, " +
"birthdate = ?, " +
"sex = ?, " +
"sss_no = ?, " +
"tin_no = ? " +
"where id_no = ?";
insertSql = "insert into dim_employees " +
"(id_no, last_name, first_name, " +
"middle_name,birthdate, sex, sss_no, tin_no) " +
"values (?,?,?,?,?,?,?,?)";
employeesStmt = con.createStatement();
employeeStmt = con.prepareStatement(employeeSql);
updateStmt = con.prepareStatement(updateSql);
insertStmt = con.prepareStatement(insertSql);
employeesCursor = employeesStmt.executeQuery(employeesSql);
while (employeesCursor.next()) {
idNo = new String(employeesCursor.getBytes(1), "UTF-8");
lastName = new String(employeesCursor.getBytes(2), "UTF-8");
firstName = new String(employeesCursor.getBytes(3), "UTF-8");
middleName = new String(employeesCursor.getBytes(4), "UTF-8");
birthDate = employeesCursor.getDate(5);
sex = new String(employeesCursor.getBytes(6), "UTF-8");
sssNo = new String(employeesCursor.getBytes(7), "UTF-8");
tinNo = new String(employeesCursor.getBytes(8), "UTF-8");
employeeStmt.setString(1, idNo);
employeeCursor = employeeStmt.executeQuery();
while (employeeCursor.next()) {
if (employeeCursor.getInt(1) > 0) {
//update
updateStmt.setString(1, lastName);
updateStmt.setString(2, firstName);
updateStmt.setString(3, middleName);
updateStmt.setDate(4, birthDate);
updateStmt.setString(5, sex);
updateStmt.setString(6, sssNo);
updateStmt.setString(7, tinNo);
updateStmt.setString(8, idNo);
updateStmt.executeUpdate();
updateStmt.executeUpdate();
}
else {
//insert
insertStmt.setString(1, idNo);
insertStmt.setString(2,lastName);
insertStmt.setString(3, firstName);
insertStmt.setString(4, middleName);
insertStmt.setDate(5, birthDate);
insertStmt.setString(6, sex);
insertStmt.setString(7, sssNo);
***//exception points here** insertStmt.setString(8, tinNo);
insertStmt.executeUpdate();
insertStmt.clearParameters();
}
}
employeeStmt.clearParameters();
Stack trace:
......
Caused by: java.lang.ArrayStoreException
at java.lang.String.getChars(String.java:854)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4520)
......
at com.vdc.lmsprocs.EmployeeProc.setEmployees(EmployeeProc.java:135)
......
I'm sorry for the long post. I clearly could not explain well enough what happened here. It's the first time i've encountered such a flaw.
Thanks in advance.

Categories