This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 6 years ago.
I just learned about prepared statements and now I'm trying to include them to my java program. However I get an exception when I try to add to values to the statement( table and name). When I prepare with only one variable it works fine.
What am I doing wrong?
[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)
String sql="SELECT * FROM ? WHERE name = ?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, table);
preparedStatement.setString(2, name);
ResultSet checkTable = preparedStatement.executeQuery();
That's not how prepared statements work. Oddly enough, you can't use placeholders for table names. The solution being to use something like:
String sql = String.format("SELECT * FROM %s WHERE name = ?", table);
... and proceed with the rest of your code.
Prepared statement are for values, a table name is not considered as being a value. So what you try to achieve is not possible.
That would work, though :
String sql="SELECT * FROM any_table_name WHERE name = ?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
ResultSet checkTable = preparedStatement.executeQuery();
} catch (Exception e) {}
Prepared statements are for column values not table names. You should do it as follows.
String sql = "SELECT * FROM `" + table + "` WHERE name = ?";
Related
This question already has answers here:
Having a Column name as Input Parameter of a PreparedStatement
(1 answer)
PreparedStatement: Can I supply the column name as parameter?
(4 answers)
Dynamic column name using prepared statement + sql query with variable containing 's
(1 answer)
Closed 1 year ago.
I'm using below code to print columns from a tables using PreparedStatement:
public static void main(String[] args) throws SQLException {
String url = "jdbc:mysql://localhost/javatesting";
Connection con = DriverManager.getConnection(url, "root", "password");
PreparedStatement preparedStatement = con.prepareStatement("Select ?,?,? from test where salary> ?");
preparedStatement.setString(1, "name");
preparedStatement.setString(2, "dept");
preparedStatement.setString(3, "salary");
preparedStatement.setInt(4, 25000);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("name")+","+resultSet.getString("dept")+","+
resultSet.getString("salary"));
}
The output of above code looks like this:
name,dept,salary
name,dept,salary
name,dept,salary
There are actual(valid) values in the table, still I end up printing the column names instead of values.
The output that I'm expecting to get printed looks something like this:
Ben,IT,30000
Marie,BPO,35000
Subash,IT,30000
The problem is that the PreparedStatement escapes the values that are passed via a ?.
So name becomes "name" and SELECT "name" always returns name.
You should change your query:
SELECT name, dept, salary FROM test WHERE salary > ?
preparedStatement.setInt(1, 25000);
This question already has answers here:
Variable column names using prepared statements
(7 answers)
Closed 4 years ago.
In a university task I'm using JDBC to access a database. I wrote a finder-method that could find objects in a table by any value in any column that has integer values.
public ResultSet findSampleByAnyCol(String colName, Integer sampleId, Connection con) {
ResultSet rs = null;
String sql = "SELECT * FROM sample WHERE ? = ?";
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, colName);
pstmt.setInt(2, sampleId);
rs = pstmt.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
return rs;
}
I tested it and I'm sure the problem is that "?" for the colum nname doesn't work. The stack trace says "invalid number". But if I change the SQL statement to SELECT * FROM sample WHERE sampleid = ? it works fine.
Just found the answer here, it´s not possible to do that. The "?" is just for values. To have variable columnnames it´s inevitable to do it with an own string manipulation.
This question already has an answer here:
ResultSet is not for INSERT query? Error message: Type mismatch: cannot convert from int to String
(1 answer)
Closed 5 years ago.
I am getting a error on the resultset rs part where netbeans shows the error as
incompatible types:int cannot be converted to resultset
Class.forName("java.sql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=false", "root", "abc");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM patient WHERE Mobile_No='" + mobno + "';"; /*Get the value from the database*/
ResultSet rs = stmt.executeUpdate(query);/*Part where the error is appearing*/
while (rs.next()) {
String Name = rs.getString("Name");
String Age = rs.getString("Age");
String Mobile = rs.getString("Mobile_No");
String gender = rs.getString("Gender");
String symptoms = rs.getString("Symptoms");
model.addRow(new Object[]{Name, Age, Mobile, gender, symptoms});
}
rs.close();
stmt.close();
conn.close();
Use stmt.executeQuery(String sql), it returns ResultSet.
If you want a ResultSet returned you should use executeQuery, not executeUpdate.
The stmt.executeUpdate(query); doesn't fit for an SELECT query.
You need to replace it by stmt.executeQuery(query);
Well the method executeUpdate returns a int not a results set, seen in the documentation here: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
the integer being return being either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
the method you are actually want to use is executeQuery and the documentation for that can be found at:
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
According the Javadoc (https://docs.oracle.com/javase/9/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-), stmt.executeUpdate(query); returns an int and not a ResultSet object.
From the Javadoc :
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
I think you must use stmt.executeQuery(query); instead, which return the ResultSet you expect. You're doing a SELECT and not an INSERT, UPDATE, or DELETE operation.
I believe people have already answered your question, which is statement.executeUpdate(query) returns the number of how many rows has been affected by executing the query, and you should use statement.executeQuery(query) instead ..
But this part String query = "SELECT * FROM patient WHERE Mobile_No = '" + mobno + "';" is very bad approach, it will leave the door opened for SQL injection, you should use PreparedStatement instead of Statement
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 7 years ago.
Is there a limit to PreparedStatement variables (?) or requirements for their placement?
I have a method that takes in the parameters to complete a PreparedStatement however, it throws a SQLException.
Here is the PreparedStatement I want to use:
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
When I add in the first and second variables it runs just fine. Here is the working PreparedStatement:
String update = "UPDATE Student SET First_Name = ? WHERE UserID = ?";
Is there a reason I cannot get the first statement to work?
The entire method:
public static void runUpdate(String givenID, String givenAttribute, String givenUpdate) throws SQLException
{
// Establish the connection with the database
Connection conn = SimpleDataSource.getConnection();
try
{
// Create a string with the SQL Update statement
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
// Make a Prepared Statement with the connection to the database
PreparedStatement stat = conn.prepareStatement(update);
try
{
// Set the statement with the given parameters
stat.setString(1, Utility.getType(givenID));
stat.setString(2, givenAttribute);
stat.setString(2, givenUpdate);
stat.setString(3, givenID);
// Execute the Update Statement
stat.executeUpdate();
}
finally
{
// Close the prepared Statement
stat.close();
}
}
finally
{
// Close the connection to the database
conn.close();
}
}
You can't use the query like this.
String update = "UPDATE ? SET ? = ? WHERE UserID = ?";
You should write the name of table and the name of the column like here.
String update = "UPDATE table SET column_name = ? WHERE UserID = ?";
You can use variables in prepared statements only as placeholder of literals in SQL statements. So you cannot use them for column name, or table names. For these you should resort to dynamic SQL statements.
Following is my code line :
ResultSet rs3 = stmt6.executeQuery("SELECT * FROM ShopSystem.Order where s_id="+s_id+" AND status="+Pending);
I am getting the following error :
Unknown column 'Pending' in 'where clause'
What could be the reason... I cant get through it..
No doubt, status is a string, so it needs to be compared to a string. Use delimiters:
SELECT * FROM ShopSystem.Order where s_id="+s_id+" AND status='"+Pending+"'"
Or better yet, learn how to write code that uses parameter substitution for putting parameter values into SQL strings.
Change it to
AND status = '" + Pending + "'"
You need to put the string in quotes. Otherwise the DB thinks you mean a column name.
But actually you should use Prepared Statements. Then you don't need to patch the queries together like this and you don't worry about parameters and escaping them...
Don't make concatenation ! Use prepared statements
PreparedStatement stm = conn.prepareStatement("SELECT * FROM ShopSystem.Order where s_id = ? AND status = ?");
stm.setInt(1, s_id);
stm.setString(2, Pending.name());
ResultSet rs = stm.executeQuery();
you must use the PreparedStatement in this case
// use the ? for the 2 entries values
String selectSQL = new String("SELECT * FROM ShopSystem.Order where s_id=? AND status=?")
preparedStatement = dbConnection.prepareStatement(selectSQL);
// in order you must incialise them here
preparedStatement.setString(1, "s_id");
preparedStatement.setString(2, "Pending");
//execute your resultset `enter code here`
ResultSet rs = preparedStatement.executeQuery();