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
Related
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.
//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();
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);
}
}
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.
I'm trying to get data from DB.
I must use to queries.
From the first query (In Loop) I get the code of Work codew and the I use it in the second query to get names.
Here's the code works without errors.
The first query fetch rows but the second is not executed.
int i=0;
c= new Connect().getCon();
try{
java.sql.Statement st = c.createStatement();
String sql= " SELECT distinct(s.codew), title, nberstat, desc_w, dated,datef" +
" FROM work w, employe e, stat s " +
" WHERE w.codew=s.codew " +
" and s.idemploye= e.idemploye " +
" and stat_w=0 " +
" and w.idcreator= 1";
System.out.println(sql);
ResultSet res = (ResultSet) st.executeQuery(sql);
String allW ="";
while (res.next())
{
String codew = res.getString("codew");
String title = res.getString("title");
String desc_w = res.getString("desc_w");
String dated = res.getString("dated");
String date = res.getString("datef");
int nberstat = res.getInt("nberstat"); String strnberstat = Integer.toString(nberstat);
///////////////////////////////////
try
{
java.sql.Statement st2 = c.createStatement();
q="SELECT distinct (name), lname From stat s, employe e WHERE codew LIKE '"+codew+"'";
ResultSet res2 = (ResultSet) st2.executeQuery(q);
while (res2.next())
{
String name = res.getString("name");
String lname = res.getString("lname");
allW = name + " "+lname+", "+allW;
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
/////////////////////////////
........
}
c.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
I get this in the console for the second query! SQL code does not execute.
Thanks in advance.
Best regards,
Ali
First of all you should use PreparedStatement with sql parameters "?" to prevent Sql injections.
Secondly, you are using the wrong statement in the second loop. You should be using res2 not res.
This should be:
String name = res2.getString("name"); //not res
String lname = res2.getString("lname"); //not res
Thirdly, you should add a finally{} block and close your connection.