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);
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 am trying to insert user information taken from a registration form into Derby DB using a java servlet class.
I get connected to the DB on NetBeans right after the user clicks the submit button with the user's information filled out. Then it should run this method:
public void insertNewUser(String userName, String passWord, String lastName, String firstName, String age, char sex, String email) {
try {
stmt = conn.createStatement();
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES ('" + userName + "', '" + passWord + "', '" + lastName + "', '" + firstName + "', " + age + ", '" + sex + "', '" + email + "')";
System.out.println(insertNewUserSQL);
stmt.executeQuery(insertNewUserSQL);
stmt.close();
} catch(SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
But I keep getting the following exception:
java.sql.SQLException: executeQuery method can not be used for update.
What does this mean exactly?
The SQL command is correct as I can do it manually on NetBeans SQL Command window.
Are there restrictions for servlets or something I don't know about?
Thanks in advance!
Since you are inserting a record, you should be using executeUpdate() not executeQuery().
Here are some methods that are usually misused:
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may
be any kind of SQL statement.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns
the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which
must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement
that returns nothing, such as a DDL statement.
One more thing, your query is weak as it is vulnerable with SQL Injection. Please do parameterized by using PreparedStatement.
Sample Code Snippet:
String insertNewUserSQL = "INSERT INTO " + studentsTable + " VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(insertNewUserSQL);
pstmt.setString(1, userName);
// ... repeat this step until the last parameter ....
pstmt.setString(7, email);
pstmt.executeUpdate();
Java PreparedStatement
To update values you need to use an updatable ResultSet, as follows:
ResultSet res = preparedStatement.executeQuery(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
res.first();
res.updateInt("id", 2);
res.updateRow();
Alternatively, you can use the executeUpdate method of statement, as follows:
statement.executeUpdate("update table set id = 2");
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
Similar question to:
Strange problem with JDBC, select returns null
but people didn't ask for this.
My code:
public int myMethod(String day) throws SQLException{
String sql = "Select count(*) from MyTable WHERE someColumn = " + day;
Connection connection = ConnFactory.get();
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;
int ret = -1;
try{
prepareStatement = connection.prepareStatement(sql);
resultSet = prepareStatement.executeQuery(sql);
if(resultSet.next()){
ret = resultSet.getInt(1);
}
}
catch(SQLException sqle){
// closing statement & ResultSet, log and throw exception
}
finally{
// closing statement & ResultSet
}
ConnFactory.kill(connection);
return ret;
}
This code always return 0. I try to log sql before execution and try to run it in SQLdeveloper and get correct value (over 100).
When I remove WHERE, sql = "Select count(*) from MyTable query return number of all rows in table.
I use Oracle 10g with ojdbc-14.jar (last version from maven repo) and Java 6.
day has not been quoted correctly, I would suggest using a prepared statement like a prepared statement as follows:
...
try {
prepareStatement = connection.prepareStatement("Select count(*) from MyTable WHERE someColumn = ?");
prepareStatement.setString(1,day);
...
is the same as:
sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
with several advantages over the latter (mainly security and performance). See:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
First of all using sql like this is not advisable. Because it leads to SQL injection.
In the future try using like below and use PreparedStatement to execute
String sql = "Select count(*) from MyTable WHERE someColumn = ? "
For your solution did you try
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";
karim79 is good answer, you forgot add apostrophe signs in your "day" value
String sql = "Select count(*) from MyTable WHERE someColumn = '" + day + "'";