I am trying to update a field in my table using Netbeans. The update statement is as follows:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student_reg";
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url,"user","abc");
PreparedStatement state = con.prepareStatement("UPDATE supplier SET sname='" + txtname.getText()+"' , add='"+txtadd.getText()+"' WHERE sid ='" +txtid.getText() + "'");
state.executeUpdate();
JOptionPane.showMessageDialog(null, "Your Record sucessfully Updated");
}catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
but I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQL SyntaxErrorException:
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 'add=kegalle'where sid=001" at line 1
How can I solve it?
You need to escape reserved words in MySQL like add with backticks
UPDATE supplier
SET sname='" + txtname.getText()+"', `add` = ...
here ---------------^---^
BTW you are not using prepared statement correctly.
The problem seems to be the way you're using PreparedStatement. Try this:
PreparedStatement state = con.prepareStatement("UPDATE supplier SET sname = ?, add = ? WHERE sid = ?");
state.setString(1,txtname.getText()); // sname (parameter 1)
state.setString(2,txtadd.getText()); // add (parameter 2)
state.setString(3,txtid.getText()); //sid (parameter 3) is actually a varchar?
state.executeUpdate();
Related
The query inside MySQL is working:
DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'
I can delete data inside MySQL, but the problem is whenever I try to remove the account_tags from my Java application, it throws an error:
java.sql.SQLSyntaxErrorException: 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 'DELETE FROM f9.yoo
WHERE account_tags = '#8GGGJPUR9'' at line 2
Here's my Java SQL query:
Statement statement = dbConnection.createStatement();
String sql = "SELECT * FROM "+databaseName+"."+tableName+";\n" +
"DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = '"+AccountTag+"';";
statement.executeQuery(sql);
The error isn't giving me much to work with, so I really have no idea what is wrong with the program.
Did you add the allowMultiQueries=true
If not then you can add that while you sending the connecting request to your database. So you need to append the allowMultiQueries=true in your to database URL.
Like this:
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
String sql = "DELETE FROM "+databaseName+"."+tableName+"\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
int updateCount = statement.executeUpdate();
System.out.printf("%s: %d records deleted.%n", tableName, updateCount);
}
The only thing used is the DELETE, for which one should use executeUpdate.
One definitely should use a PreparedStatement as many code checkers will give alarms otherwise. It escapes things like ', handles types of the arguments, and possible conversions, and especially is a security feature against SQL injection.
The System.out usage is bad style, better would be using a logger.
try-with-resources automatically closes the PreparedStatement even with a raised exception or break/return.
When doing both database operations, it seems better to use two (prepared) statements, as the first returns a ResultSet.
So:
String sql = SELECT * FROM "+databaseName+"."+tableName + "\n" +
"WHERE account_tags = ?";
try (PreparedStatement statement = dbConnection.prepareStatement(sq)) {
statement.setString(1, AccountTag);
try (ResultSet rs = statement.executeQuery()) {
...
}
}
Better to separate statements with an If condition :
String sql1="SELECT * FROM "+databaseName+"."+tableName;
String sql2="DELETE FROM "+databaseName+"."+tableName+" "+
"WHERE account_tags = '"+AccountTag+"';
statement.executeQuery(sql1);
statement.executeUpdate(sql2);
see the screenshots
see the 2nd screenshot
see the 3rd screenshot
Okay so I am building a project on java and mysql, I am stuck at this point that I have to update a data which is in MySql but from my java gui application, I've executed that update command from MySql command line client
update user set bldu = 50 where userid = 1001;
and it's working perfectly fine there but from my java application on clicking on assigned jbutton it says:
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 'userid= 1001' at line 1
Please help me..!
In your first screenshot you must add a space before WHERE clause:
String query = "UPDATE user SET bdlu = " + bldut + "WHERE userid = " + uid + ";";
So your query will be interpretated as:
UPDATE user SET bdlu = 50WHERE userid = 1001
So you'll raise a syntax error.
Then you'll have the following query:
String query = "UPDATE user SET bdlu = " + bldut + " WHERE userid = " + uid + ";";
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
use this one instead of your old query may be it is helpful for you.
Try this snippet in your code.
String query = "update user SET bldu = " + bldut + " WHERE userid = " + uid + ";";
Statement = con.prepareStatement(query);
Statement.executeUpdate();
by looking at your code you cannot store results of update query in resultSet the executeUpdate() only return 0 or 1 for success and failure of Update.
Okay i guys i have figured out something that it is working i mean this program is updating the data stored in mysql from netbeans via jdbc but it won't stop showing that error message like:
"Can not issue data manipulation statements with executeQuery()"
everytime i click one that assigned jButton..! but i checked the database the value i want to change is being changed but then why it is showing this error..?
Please use this code in your java file, do changes according to your file. your issue is you are using the same query in a result set that already uses for the update
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bdb", "root", "root");
try {
String query = "update user SET bldu = " + bldut+ " WHERE userid = " + uid + ";";
// create the java mysql update preparedstatement
Class.forName("com.mysql.jdbc.Driver").newInstance();
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.executeUpdate();
query = "select * from user WHERE userid = " + uid +";";
ResultSet rs = stmt.executeQuery(query);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String userid = rs.getString("userid");
String userfname = rs.getString("userfname");
// all your column
// Display values
System.out.print("userid: " + userid);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
} finally {
// finally block used to close resources
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}// end finally try
}// end try
//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();
My java code for SQL Query is
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
I have tried out
name= a'); DROP TABLE users; --
as well as
place =a'); DROP TABLE users; --
but it returns an Ecxeption as below
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 'DROP TABLE users; --','chennai')' at line 1
Note: when i tried the same in mysql command line. It worked!!!! i don't know what happens in jdbc
The real problem is actually JDBC, it only allows one sql if you dont tell it otherwise.
Look at this question for more info:
Multiple queries executed in java in single statement
But also i would try this instead, name =
a',''); DROP TABLE users; --
Since you specificed 3 columns in your insert:
(id,name,place)
You need to provide 3 values for the sql to be valid, not just 2.
Also you can sent the text null, sending a java null value is not necessary and i am not even sure how that works. I think this might be better:
String sqlSt="INSERT INTO users(id,name,place) values (null,'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
Instead of null, use an empty string ''
String sqlSt = "INSERT INTO users(id, name, place) values ('', '" + request.getParameter("name") + "', '" + request.getParameter("place") + "');";
It's better to use prepared statements to avoid confusion.
String sqlSt = "INSERT INTO users(id, name, place) values ('', ?, ?)";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(query);
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("place"));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
ps.close();
}
The real problem is with your Query. It is better to use a PreparedStatement for executing a query.
Your Code should be :
String sqlSt="INSERT INTO users(id,name,place) values (?,?,?)";
PreparedStatement pstmt = null;
try{
pstmt = dbConnection.prepareStatement(sqlSt);
pstmt.setString(1,null);
pstmt.setString(2,request.getParameter("name"));
pstmt.setString(3,request.getParameter("place"));
pstmt.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
}
If you don't want to use a PreparedStatement, just remove last ; from your query.
So your query will be :
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"')";
So this is my code
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/test";
//ResultSet rs = null;
PreparedStatement psmnt = null;
//FileInputStream fis;
connection = DriverManager.getConnection(connectionURL,"root","123");
psmnt = connection.prepareStatement("insert into Table1 (name, desc, r,g,b," +
"varR,varG,varB,skewnessR,skewnessG,skewnessB)values(?,?,?,?,?,?,?,?,?,?,?)");
final String text2 = setName.getText();
final String text3=setDesc.getText();
psmnt.setString(1,text2);
psmnt.setString(2,text3);
psmnt.setString(3,stringMeanR);
psmnt.setString(4,stringMeanG);
psmnt.setString(5,stringMeanB);
psmnt.setString(6,stringVarianceR);
psmnt.setString(7,stringVarianceG);
psmnt.setString(8,stringVarianceB);
psmnt.setString(9,stringSkewnessR);
psmnt.setString(10,stringSkewnessG);
psmnt.setString(11,stringSkewnessB);
//fis = new FileInputStream(f);
//psmnt.setBinaryStream(2, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
psmnt.close();
connection.close();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("Unsucessfull to upload image.");
}
The problem is that i get the following error
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 'desc, r,g,b,varR,varG,varB,skewnessR,skewnessG,skewnessB)values('','','105.59 , ' at line 1
desc is a reserved SQL keyword (used in order by foo desc). Change the name of the column you named "desc" (or escape it using backticks, but I would change the name to make it easier)
desc is a reserved keyword in SQL for describing an SQL table. As a result, if your column name is 'description' then it should be 'description'; not 'desc' as desc is reserved in MySQL for describing the table itself or showing the SQL code for the creation of the table.