Iam using a Java Swing Application to Update a column in Mysql table. Here is My code(part)
String qunty = txtWithdraw.getText();
String partno = txtNo.getText();
int qty = Integer.parseInt(qunty);
con = DriverManager.getConnection(url + db, "username", "password");
Statement st = con.createStatement();
String sell = "update Store_info_table set qnty_received = qnty_received - " + qty + "where Part_number = '" + partno + "'";
st.executeUpdate(sell);
I am getting the Exception that:
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 'Part_number = 'DF6534'' at line 1
I want to Update the qnty_received field so that it is equal to the Original value minus the value passed by the user i.e (int qty). What Error Am I making?
Add a space before the where:
" where Part_number = '" + partno + "'";
As a good practice, I recommend you to use PreparedStatement and set your parameters with the same. Concatenating the parameters dynamically may force the db engine to parse a new SQL statement every time.
A SQL statement is precompiled and stored in a PreparedStatement
object. This object can then be used to efficiently execute this
statement multiple times.
See: PreparedStatement
Missing space:
... + qty + "where ...
^--- here
which makes your query something like
... qnty_received - blahwhere
Related
I'm currently working on a project where we have an inventory for an optical lens company which is stored in a database. I've connected my database to my java program and im just having an issue selecting a row based on a column value. Im doing this by
String name=lookUpName.getText();
try (
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/productitem?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"root", "123456789"); // for MySQL only
Statement stmt = conn.createStatement();
) {
String strSelect = "select * from products where productName= "+name+"";
System.out.println("The SQL statement is: " + strSelect + "\n"); // Echo For debugging
ResultSet rset = stmt.executeQuery(strSelect);
}
rset.close();
when it tries to execute the query it gives me an error. but if i run a regular query using the sql console like select *
from products where productName='golden vintage'; it works. can someone help me with the java part.
the debugging output i have in there shows
The SQL statement is: select * from products where productName= golden vintage
The error I get is:
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 'vintage' at line 1
I figured it out using the Prepared Statements
String strSelect = "select * from products where productName= ?";
PreparedStatement st = conn.prepareStatement(strSelect);
st.setString(1,name);
ResultSet rs = st.executeQuery();
while (rs.next()) {
String productid = rs.getString(1);
String productColors=rs.getString(2);
String productPrices = rs.getString(3);
String productBrands=rs.getString(4);
String productStyles = rs.getString(5);
String productNames=rs.getString(6);
System.out.println(productid +" "+productNames + " " +productBrands + " " + productStyles + " " + productColors + " " + productPrices);
}
I am trying to run a SQL statement in Java and I am getting syntax
String number,key; //populate number and key.
rs = stmt.executeQuery("select count(*)
from users_transition
where phoneNumber =" +number +"and randKey="+key);
In MySQL database, phoneNumber is BigInt(20) and key is Int(11).
Also, according to this link. The table 5.1 says that types in MYSQl can be converted to what types in Java. Doesnt the other way round would work too?
Here's the 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 'randKey=9999' at line 1
You are missing a space between the number and the AND operator:
rs = stmt.executeQuery("select count(*) from users_transition where phoneNumber =" +number +" and randKey="+key);
// ^
You should replace the query with prepared statement, and use query parameters. This would help you not only avoid simple errors like this, but also make your code immune to SQL injection attacks.
String sql = "select count(*) from users_transition where phoneNumber =? and randKey=?";
PreparedStatement getCount = con.prepareStatement(sql);
getCount.setBigDecimal(1, new BigDecimal(number));
getCount.setBigDecimal(2, new BigDecimal(randKey));
I'll tell you what is wrong, and then I'll tell you what is very wrong.
What is wrong
First, you are building a query which where has missing spaces (and possibly missing quotes):
String number,key; //populate number and key.
rs = stmt.executeQuery("select count(*) "
+ "from users_transition "
+ "where phoneNumber =" +number +" and randKey="+key)";
// ^ you missed a space here
What is very wrong
Your query is vulnerable to SQL Injection Attacks (please read the link, it provides a humorous example and tips on solving the problem). Use prepared statements to do this kind of thing:
String number, key;
PreparedStatement ps = conn.prepareStatement("select count(*) "
+ "from users_transition "
+ "where phoneNumber=? "
+ " and randKey=?");
// The question marks are place holders for values
// You can assign this values with setXXX() methods
ps.setString(1, number);
ps.setString(2, randKey);
ResultSet rs = ps.executeQuery();
// Do whatever you need to do with the ResultSet
I made a simple insert into statement but it is not working well. The error that it gives to me is
com.mysql.jdbc.exceptions.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 'From, To, Message,
Date, Read) VALUES (3,1,'iepa','2012-10-16 16:26:42',0)' at line 1
this is the code of my sql.
Connection conn = Connect.getConnection();
try{
Statement stmt = conn.createStatement();
String sql = "INSERT INTO MESSAGE("
+ "From,"
+ "To,"
+ "Message,"
+ "Date,"
+ "Read) "
+ "VALUES(?,?,?,?,?)";
PreparedStatement pstat = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstat.setInt(1, user.getId());
pstat.setInt(2, Integer.parseInt(who.getText().toString()));
pstat.setString(3, message.toString());
pstat.setTimestamp(4, new Timestamp(new Date().getTime()));
pstat.setInt(5, 0);
pstat.executeUpdate();
As you see I am not doing nothing strange or so difficult but I cannot run it.
You need to escape reserved words in MySQL like from with backticks
String sql = "INSERT INTO MESSAGE("
+ "`From`,"
+ "`To`,"
+ "Message,"
+ "Date,"
+ "`Read`) "
+ "VALUES(?,?,?,?,?)";
Change From,Read and Date to any other column name which is not a SQL keyword.
Find list of Reserved Words in MySQL
I have set up a program for an enterprise to handle their brochures(catalogo in spanish).
I ask the user via Swings for the data, and then use it to generate a query and insert it into my db.
Here is the code:
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(false);
st = con.createStatement();
String sql = "INSERT INTO `catalogos` (`id`, `name`, `keywords`) VALUES(" + catNumIn.getText() + ", '" + catNameIn.getText() + "', '" + catKeyIn.getText() + "');";
st.executeUpdate(sql);
So i would like to know what my error is. Thank you!
Are you committing your transaction? You've said setAutoCommit(false) after all. Could you try:
setAutoCommit(true);
instead of the line you currently have, or:
con.commit();
after your database update?
When you construct sql statement in your front end and have an error, the best approach is to print the variable and see if there is a problem with the values like single quotes,missing comma,etc
I am working with a Java prepared statement that gets data from an Oracle database. Due to some performance problems, the query uses a "virtual column" as an index.
The query looks like this:
String status = "processed";
String customerId = 123;
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = " + status + " AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.execute();
...
} catch (...)
This does not work. Having the function as part of the where clause causes a SQLException. I am aware of CallableStatement, and know I could use that first and then concatenate the results. However, this table uses FN_GET_CUST_ID(trans_id) as part of it's index. Is there a way to use a prepared statement with a database function as a query parameter?
Never concatenate arguments for the SQL into the String. Always use placeholders (?) and setXxx(column, value);.
You'll get the same error if you'd run the SQL in a your favorite DB tool. The problem is that Oracle can't use the function for some reason. What error code do you get?
If Customer ID is numeric keep in int not in String. Then try doing the following:
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = ? AND FN_GET_CUST_ID(trans.trans_id) = ?";
ps = conn.prepareStatement(query);
ps.setString(1, status);
ps.setInt(2, customerId);
ps.execute();
Besides other benefits of prepared statement you won't have to remember about string quotations (this causes your error most likely) and escaping of the special characters.
At the first glance, the query seems to be incorrect. You are missing an apostrophe before and after the usage of status variable (assuming that status is a varchar column).
String query = "SELECT DISTINCT trans_id FROM trans
WHERE status = '" + status + "' AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
EDIT: I am not from java background. However, as #Aron has said, it is better to use placeholders & then use some method to set values for parameters to avoid SQL Injection.