JAVA + Mysql PreparedStatement.setString() ArrayStoreException - java

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.

Related

Why SQL UPDATE actually performs a DELETE instead?

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

ResultSet with variable

Ok so basically I have this code:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
private void writeResultSet(ResultSet resultSet) throws SQLException {
System.out.println("jestem w writeresultset");
// resultSet is initialised before the first data set
while (resultSet.next()) {
// it is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g., resultSet.getSTring(2);
String id = resultSet.getString("id");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user
+ " nazwisko to " + website + " adres to " + summary + " email to "
+ date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
}
What I want to achieve is this:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS
where NAZWISKO LIKE " variable );
writeResultSet(resultSet);
I want to search by variable which is already defined, however I'm stuck and have no idea how to do it like that.
Use PreparedStatement:
String nazwisko = ...
String query = "select * from FEEDBACK.COMMENTS where NAZWISKO LIKE ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, nazwisko);
ResultSet rs = pstmt.execute();
while (resultSet.next()) {
//...
}
In case you need to use a wildcard for your LIKE, choose one of these:
nazwisko = nazwisko + "%";
nazwisko = "%" + nazwisko;
nazwisko = "%" + nazwisko + "%";
up , there are alot weird errors with your code:
like cannot find symbol variable con or incompatible type boolean cannot be converted to resultset.
I have tried this: but there is an error when executing
preparedStatement = connect
.prepareStatement("select * from FEEDBACK.COMMENTS where NAZWISKO= ? ; ");
preparedStatement.setString(1, surname3);
while (resultSet.next()) {
String id = resultSet.getString("i
d");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user + " nazwisko to " + website + " adres to " + summary + " email to " + date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
error:
the query went fine but , the error appears here "while (resultSet.next())"
SEVERE: null
java.lang.NullPointerException
at jdbcexample.Main.readDataBase(Main.java:416)
at jdbcexample.Main$7.mousePressed(Main.java:346)

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

DB2 Error SQLCODE=-103, SQLSTATE=42604

I am trying to update a table, but it isn't working and giving this sql error.
//Updating Buy Table
Integer stkbid = Integer.parseInt(request.getParameter("stockBid"));
System.out.println("stock buy id : " + stkbid);
//get buy details
PreparedStatement stmtbuy = conn.prepareStatement(
"SELECT \"StockSymbol\", \"Unit\", \"Price\", \"ClearingFee\", \"StampDuty\", \"BrokerFee\"" +
"FROM SPM.\"StockBuy\" WHERE \"StockBuyId\" = '"+ stkbid + "'");
System.out.println("Got stock buy details");
ResultSet rs=stmtbuy.executeQuery();
rs.next();
//String stkcode = rs.getString("StockSymbol");
Integer stkunit = Integer.parseInt(rs.getString("Unit"));
stkunit -= stock.getStockUnit();
Double stkprice = Double.parseDouble(rs.getString("Price"));
Double stkclear = Double.parseDouble(rs.getString("ClearingFee"));
Double stksd = Double.parseDouble(rs.getString("StampDuty"));
Double stkbfee = Double.parseDouble(rs.getString("BrokerFee"));
Double stkval = stkunit * stkprice;
Double stknv = stkval + stkval * (stkclear + stksd + stkbfee);
System.out.println(stknv);
PreparedStatement stmtbuy1 = conn.prepareStatement(
"UPDATE SPM.\"StockBuy\" SET \"Unit\" = " + stkunit + ", \"Value\" = " + stkval + ", \"NetValue\" = " + stknv +
"WHERE \"StockBuyId\" = "+ stkbid);
You are missing a space in before the WHERE clause, which messed up your stknv.
" WHERE \"StockBuyId\" = "+ stkbid);
I think it's an obligation of any poster to remind you that you should use parametrized query. So I shall do the same.
"Please use parametrized query!"
The query that is works has a quote at the end:
" WHERE \"StockBuyId\" = '"+ stkbid + "'");
The one that fails does not
"WHERE \"StockBuyId\" = "+ stkbid);
That might have something to do with it.

Spring JdbcTemplate Cannot Get Insert ID from MySQL

I am trying to insert a row into a MySQL table and get it's insert ID. I am aware of the MySQL last_insert_id() function, I just cannot seem to get it to work. Currently, I am trying to use a function annotated as a transaction and I am only getting 0 returned. I am using Spring 3.1.
#Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private long insertTransactionRecord
(
int custID,
int porID,
String date,
short crvID
) {
m_template.update ("INSERT INTO " +
" transaction " +
"( " +
" por_id, " +
" cust_id, " +
" trans_date, " +
" crv_id " +
") " +
"VALUES " +
"( " +
" ?, " +
" ?, " +
" ?, " +
" ? " +
")",
new Object[] {
porID,
custID,
date,
crvID
});
return m_template.queryForLong ("SELECT " +
" last_insert_id() " +
"FROM " +
" transaction " +
"LIMIT 1");
}
Use Spring's built-in support for this rather than doing it yourself.
SqlUpdate insert = new SqlUpdate(ds, "INSERT INTO company (name) VALUES (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR));
insert.setReturnGeneratedKeys(true);
// assuming auto-generated col is named 'id'
insert.setGeneratedKeysColumnNames(new String[] {"id"});
insert.compile();
....
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(new Object[]{"test"}, keyHolder);
System.out.println(keyHolder.getKey().longValue());
taken from here http://www.codefutures.com/spring-dao/
public int createCompany(Company company) throws SQLException {
jdbcTemplate.update(
"INSERT INTO company (name) VALUES (?)",
company.getName()
);
return jdbcTemplate.queryForInt( "select last_insert_id()" );
}
if you noticed there's no FROM there
The documentation reveals that the syntax for getting the last insert ID is:
SELECT LAST_INSERT_ID()

Categories