How to Print " Inside Print() Function in Java

I have the following line in my code :

int check1 = stmt3.executeUpdate("update ShopSystem.Grocery where g_id="+g_id+" set g_name="+g_name);

It is showing me the following error :

 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 'where g_id=5 set g_name=Chikoo' at line 1

I think its because what is actually being passed to the SQL Server is : "update ShopSystem.Grocery where g_id=5 set g_name=Chikoo;

g_name is actually a String type. How should I pass that as a string in java print statement? Or is there any other mistake in my syntax?

3

3 Answers

You need to supply the quotes around the text value in your query, like so:

"update ShopSystem.Grocery set g_name='"+g_name +"' where g_id="+g_id+";

However, I would firmly advise you to use parameterized queries/prepared statements instead of concatenation.

PreparedStatement stmtUpdate = null;

String strUpdate = "update ShopSystem.Grocery set g_name= ? where g_id = ?";

stmtUpdate = yourconnection.prepareStatement(strUpdate);
stmtUpdate.setString(1,g_name);
stmtUpdate.setInt(2,g_id);
stmtUpdate.executeUpdate();

Note that the above code does not include exception handling and disposing resources, but it should get you started.

2

I think g_name is a varchar type so you should enlose it with in quotes ('') like this

int check1 = stmt3.executeUpdate("update ShopSystem.Grocery set g_name='"+g_name+"' where g_id="+g_id );

As shree.pat18 says I would advise you to use parameterized queries/prepared statements:

Anyway, you can use either simple quotes as:

"simple quote here -> ' text ' <-"

or double quotes as:

"double quote here -> \" text \" <-"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest