BatchUpdateException: Unknown column in where clause - java

When writing to a mySQL db, i get the following error:
java.sql.BatchUpdateException: Unknown column 'ALFA' in 'where clause'
this is my java code:
public void pushWinner(String game, String teamW) throws SQLException{
String[] t1 = game.split("-");
String statement = "update games set winner=(?) where team1 = "+t1[0]+" AND team2 = "+t1[1];
try (PreparedStatement pstmt = conn.prepareStatement(statement)) {
pstmt.setString(1, teamW);
pstmt.addBatch();
pstmt.executeBatch();
pstmt.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
I realy can't see what's wrong with the where clause...
EDIT
See my comment, forgot to mention what 'ALFA' is.
Data types for team1 and team2 are both VARCHAR(45).

try this: since datatype of column team1 and team2 are VARCHAR so put single quote to compare it.
queryString= "update games set winner=(?) where team1 = '"+t1[0]+"' AND team2 = '"+t1[1]+"'";

If your datatype is string that you need Single Quote around your passed variable values
something like this...
String statement = "update games set winner=(?) where team1 = '"+t1[0]+"' AND team2 = ' "+ t1[1] + "'";

Your asking for trouble making sql like this. use a prepared statement with seperate parameters instead of inline param building. will stop issues like this and take care of parameter escaping. So use ? in the main sql to denoate location of a parm and use .setString(1, value); to set first (yes its 1 based). Or setInt(1, intValue) ... depending on data type. For date use java.sql.Timestamp - can convert a calendar to date and java.util.Date to sql timestamp OR new javax.time or joda. But dont use inline.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Why
ease of programming and
https://www.owasp.org/index.php/SQL_Injection
Copied from the java tutorial :
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
if (updateSales != null) {
updateSales.close();
}
if (updateTotal != null) {
updateTotal.close();
}
con.setAutoCommit(true);
}
}

Related

Java PreparedStatement doesn´t set value

I´m totally new to Java and I try to set up a little test to read some data from a MSSQL-database. I have to pass some values to the query but that does not work properly, if I set them manually it works, in my case with the PreparedStatement and the .setLong-Method it does not work.
public class db_testClass {
public static void main(String[] args) throws ClassNotFoundException {
long firstId = 0;
long lastId = 201801001010010403L;
PreparedStatement statement;
int counter = 1;
String SQL = "IF OBJECT_ID('tempdb..#tmpDaten') IS NOT NULL
" DROP TABLE #tmpDaten;
" SELECT DISTINCT
" RIGHT(10000000 + ISNULL(r.xxx, 0), 7) AS Wert
" INTO #tmpDaten
" FROM dbo.xxx
" WHERE r.xxxx BETWEEN firstId = ? AND lastId = ?;
" SELECT DISTINCT
" 'xxxx' AS Art ,
" t.xxx
" FROM #tmpDaten
" LEFT JOIN xxxxxxx a ON a.xxxx = t.xxxx
" AND a.ART = 'xxxx' " +
" WHERE a.xxxx IS NULL;";
String connectionUrl = "jdbc:sqlserver://xxxxxx:1433;databaseName=xxxxxx;integratedSecurity=true;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection con = DriverManager.getConnection(connectionUrl);
statement = con.prepareStatement(SQL);
statement.setLong(1, firstId);
statement.setLong(2, lastId);
System.out.println(statement);
ResultSet rs = statement.executeQuery();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
The error says that there is wrong syntax nearby the '='......
Anyone any ideas?
Thanks,
Daniel
Your usage of the BETWEEN operator is suspicious and probably just an outright syntax violation. It should be something like:
something BETWEEN low-value AND high-value
to test if the something lies between the values low-value and hi-value.

How can I update the ID of an entity in mysql through DAO?

//Here's my code in my AccountDAO
#Override
public void editAccount(Accounts account) throws ErrorException {
response = FAILED;
Connection connection = null;
PreparedStatement pStatement = null;
String sql = "UPDATE all_accounts SET
accountID=?,accPassword=?,accStatus=?"
+ "WHERE accountID "+ account.getAccountID();
ResultSet resultSet = null;
try {
if(manager == null){
manager = (DBManager)
DBManagerImplementation.getInstance();
}
connection = manager.getConnection();
pStatement = connection.prepareStatement(sql);
pStatement.setString(1, account.getPassword());
pStatement.setString(2, account.getStatus());
pStatement.execute();
} catch (SQLException ex) {
System.out.println("Error in editng/adding new
employee!!"+ex.toString());
}catch (Exception ex) {
System.out.println("Erroorr. super error!!"+ex.toString());
} finally{
DataDispatcher.dispatch(resultSet, pStatement, connection);
}
}
But After compiling this was my error:
Error in editng/adding new
employee!!com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
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 '111' at line 1
This is what your query looks like
"UPDATE all_accounts SET
accountID=?,accPassword=?,accStatus=?"
+ "WHERE accountID "+ account.getAccountID();
Couple of things that stand out
No space before WHERE clause
No assignment for the WHERE clause i.e.
WHERE accountID ="+ account.getAccountID();
In your sql you are using 3 parameters but you set only two.
It should set the id also before first parameters .Also take care with no space before where and WHERE accountID u need to use WHERE accountID =
You dont need to set the accountId in below query
String sql = "UPDATE all_accounts SET
accountID=?,accPassword=?,accStatus=?"
+ " WHERE accountID ="+ account.getAccountID();
Remove accountID and use this query
String sql = "UPDATE all_accounts SET
accPassword=?,accStatus=?"
+ " WHERE accountID ="+ account.getAccountID();

i want to display special characters from mysql to jtextfield using jbutton.my code is working only numbers

private void jbutton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
MainClass mc=new MainClass();
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
ResultSet rs;
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr=StrQr + " and pid = " + prid.getText().trim() + " ";
}
if (StrQr.length()==0)
{
JOptionPane.showMessageDialog(null,"Enter search critaria.");
return;
}
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");
while (rs.next()) {
purcst.setText(rs.getString("ppurcst"));
salprc.setText(rs.getString("psalprc"));
prid.setText(rs.getString("Pid"));
prname.setText(rs.getString("Pname"));
category.setText(rs.getString("Pcategory"));
cprc.setText(rs.getString("Pcmprc"));
qnty.setText(rs.getString("Pqty"));
slno.setText(rs.getString("Pslno"));
lpurcst.setText(rs.getString("plpurcst"));
}
rs.close();
}
catch (Exception e)
{
System.err.println(e);
//System.exit(1);
}
}
code display only pid = 104 like numbers .
it cant display special charectors( _,- )pid= A_1103like anybody can help me.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'A' in 'where clause'
i declare pid as varchar in mysql
A_1103 needs to be quoted, otherwise MySQL will try and resolve it to a column value.
... pid = 'A_1103' ...
In fact, you should be relying on PreparedStatement in order to prevent possible SQL injection problems.
See Using Prepared Statements for more details
For example...
Connection connection;
connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd);
ResultSet rs;
// I'm assuming there are other elements to this query that
// may be included, otherwise this is a lot of overhead
// for little benifi...
List values = new ArrayList(5);
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr += " and pid = ? ";
values.add(prid.getText().trim());
}
if (StrQr.length()==0)
{
JOptionPane.showMessageDialog(null,"Enter search critaria.");
return;
}
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
// Bind the values to the parameters
for (int index = 0; index < values.size(); index++) {
st.setObject(index + 1, values.get(index));
}
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");
In prepared statement you have to set a ? or any parameter and bind the value.
String StrQr="";
if (prid.getText().trim().length()>0 )
{
StrQr=StrQr + " and pid = ? ";
}
...
PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid");
if (prid.getText().trim().length()>0 )
st.bind(1prid.getText().trim() )
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"connected");

Java SQL (JDBC) : how to move to the next column?

I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.

Java mysql, Simple update with PreparedStatement has syntax error

This code has some sort of simple syntax error. I've fought it for hours now and I give up. Can you spot it? I bet it's easy. Thanks!
When I update just the firstname John, no problem.
When I try to update the commented out line for the lastname too, syntax error.
import java.sql.*;
public class UpdateTester {
public static void main(String[] args) {
try {
Connect connect = new Connect();
Connection connection = connect.getConnection();
try {
String sql = "UPDATE student SET firstName = ? "
+ " WHERE studentID = 456987";
//String sql = "UPDATE student SET firstName = ? "
// + " Set lastName = ?, "
// + " WHERE studentID = 456987";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, "John");
//pst.setString(2, "Johnson");
pst.executeUpdate();
System.out.println("Updated Successfully!");
connection.close();
} catch (SQLException e) {
System.out.println("Exception 1!");
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exception 2!");
e.printStackTrace();
}
}
}
Column names are correct.
Updating just the lastname on it's own works correctly too.
Update fails with syntax error when trying to do both, as in the commented out lines.
3 issues:
The SET keyword can only appear once in an UPDATE statement:
Comma before second parameter missing
Unnecessary comma before where clause
The corrected syntax:
String sql = "UPDATE student SET firstName = ?, "
+ " lastName = ? "
+ " WHERE studentID = 456987";
SQL Reference

Categories

Resources