insert into giving problems - java

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

Related

Selecting a row from sql database based on a value in a specific column in java

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);
}

java.sql.SQLSyntaxErrorExceptionORA-00933: SQL command not properly ended

I am using this query
sql=String.format("INSERT INTO PM_AM_ASSET_AUDIT(TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME)
SELECT TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME
FROM PM_AM_ASSET_MASTER where id ="+id);
preparedStatement = connection.prepareStatement(sql,new String[] {"ID"});
but, I got this exception
java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended
When I remove generated keys concept the query executes.
Newer use concatenation in your statements to prevent sql injection.
Try this case:
String sql = "INSERT INTO PM_AM_ASSET_AUDIT " +
" (TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME) " +
"SELECT TAG_ID,MODEL_ID,CATEGORY_ID,DESCRIPTION,NOTES,STATUS_ID,PARK_ID,TOWER_ID,FLOOR_ID,UNIT_ID,CUSTOMER_ID,CHECK_OUT_DATE,DUE_DATE,MODIFIED_BY,MODIFIED_DATE,REVISION,PARK_NAME,TOWER_NAME,FLOOR_NAME,UNIT_NAME,CUSTOMER_NAME " +
"FROM PM_AM_ASSET_MASTER where id = ?";
preparedStatement = connection.prepareStatement(sql);
p.setString(1, id);

Wrong SQL in Java

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

Mysql database Error while updating a field

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

Java and MySQL INSERT

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

Categories