Unknown column '$a' in 'where clause' - java

i want to fetch data from database by using a variable string.it shows error
"Unknown column '$a' in 'where clause'"
String a=request.getParameter("from");
ResultSet resultset= statement.executeQuery("select * from flight where f = $a") ;

If you want to use the value of the a variable where you have $a, you need to use a prepared statement and fill it in:
String a = request.getParameter("from");
PreparedStatement ps = connection.prepareStatement( // Create a prepared statement
"select * from flight where f = ?" // Using ? for where the
); // parameter goes
ps.setString(1, a); // Fill in the value (they
// start a 1, oddly)
ResultSet resultset = ps.executeQuery(); // Execute the query
Note that even though it's a string, you don't put quotes around the ?. The PreparedStatement handles that for you at the DB driver level, in a way that's safe from SQL injection.

Related

Passing BIT in query as a parameter in Prepared Statement

I want to pass a bit as one of the parameters in Prepared Statement. My query should look like this :
query = select * from tbl_security_details('user',O::BIT)
I am framing the query as :
query = select * from tbl_security_details(?,?)
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1,"user")
ps.setString(2,"0::BIT")
However, this throws an error.
Can someone explain how I can pass 0::BIT from the prepare statement without it appending the single quote by itself and getting converted to String ?
Write the prepared statement so that the cast is part of the query:
String query = "select * from tbl_security_details(?, ?::bit)";
java.sql.PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, "user");
ps.setString(2, "0");
That is necessary, because you can only pass a constant value to the prepared statement, not an SQL expression.

get size of ResultSet by using SELECT COUNT(*)

I want to retrieve all the data from database, and at the same time, I want to know how many rows of data I get. And this is my SQL:
rs = s.executeQuery("SELECT COUNT(*), * FROM tblUser");
Is this a valid SQL statement? and after I retrieved all the data, how to set them into different variables? For example, I have a column called UserIDin the database, I can simply get it by using rs.getString('UserID'), but how to get the result of the COUNT(*)?
Your SQL is not valid. The ANSI standard way to do what you want uses window functions:
select count(*) over () as total_cnt,
u.*
from tblUser u;
This adds a new column to every row -- which seems to be what you want. There are other mechanisms, depending on the underlying database for doing this.
The results you request are not interrelated, so run two queries:
rs1 = s.executeQuery("SELECT COUNT(*) FROM tblUser");
rs2 = s.executeQuery("SELECT * FROM tblUser");
and retrieve the values (one only for rs1) the usual way.
You can do this to count the rows in resultset
String query = "Select * from tblUser";
rs = s.executeQuery(query);
public int getCount(ResultSet rs) {
int rows = 0;
while(rs.next()) {
i++;
}
return i;
}
This way you can get the resultset as well as count
Since you are already accessing the recordset within VBA probably the simplest was to return the count of the record set is to:
rs = s.executeQuery("SELECT * FROM tblUser");
If Not rs.EOF Then
' Important: You must move to the last record to
' obtain the count of the full recordset
rs.MoveLast
rsCount = rs.RecordCount
' Remember to Return to the First Record so that you can
' continue to use the recordset
rs.MoveFirst
End If
An alternative if your RDBMS doesn't support window functions
rs = s.executeQuery("SELECT B.cnt, U.*
FROM tblUser U,
(SELECT count(*) cnt FROM tblUser) B");

why we use setInt with select query instead of using getInt when value is already there in database

why we use setInt with select query instead of using getInt when value is already there in database?
try {
conn = getConnection();
ps = conn.prepareStatement("SELECT * FROM circle where id =?");
ps.setInt(1, circleId);
Circle circle = null;
rs = ps.executeQuery();
if (rs.next()) {
//String s = rs.getString(circleId);
circle = new Circle(circleId, rs.getString("name"));
}
You're setting the value of the parameter to be used in the query. The ? in the SQL represents the parameter, and here you're giving it a value.
When you call getString() later, that's getting a value from the results of the query, which are very different from the parameters sent as part of the query.
Parameterized SQL allows safe inclusion of values into queries, without needing to escape them to prevent SQL injection attacks, or worrying about data type conversions. You should read the JDBC PreparedStatement tutorial for more details.

Unknown column error in where clause, using MySQL and Java

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

Parameterized Oracle SQL query in Java?

I've been trying to figure out why the following code is not generating any data in my ResultSet:
String sql = "SELECT STUDENT FROM SCHOOL WHERE SCHOOL = ? ";
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, "Waterloo");
ResultSet rs = prepStmt.executeQuery();
On the other hand, the following runs properly:
String sql = "SELECT STUDENT FROM SCHOOL WHERE SCHOOL = 'Waterloo' ";
PreparedStatement prepStmt = conn.prepareStatement(sql);
ResultSet rs = prepStmt.executeQuery();
The data type for SCHOOL is CHAR (9 Byte). Instead of setString, I also tried:
String sql = "SELECT STUDENT FROM SCHOOL WHERE SCHOOL = ? ";
PreparedStatement prepStmt = conn.prepareStatement(sql);
String school = "Waterloo";
Reader reader = new CharArrayReader(school.toCharArray());
prepStmt.setCharacterStream(1, reader, 9);
prepStmt.setString(1, "Waterloo");
ResultSet rs = prepStmt.executeQuery();
I'm completely stuck on what to investigate next; the Eclipse debugger says the SQL query doesn't change even after setString or setCharacterStream. I'm not sure if it's because setting parameters isn't working, or if the debugger simply can't pick up changes in the PreparedStatement.
Any help will be greatly appreciated, thanks!
I think the problem is that your datatype is CHAR(9) and "Waterloo" has only 8 chars.
I assume that this would return the expected results (LIKE and %). Or add the missing space.
String sql = "SELECT STUDENT FROM SCHOOL WHERE SCHOOL LIKE ? ";
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, "Waterloo%");
ResultSet rs = prepStmt.executeQuery();
The best way would by to use varchar instead of char if your Strings have a flexible length. Then the PreparedStatement would work as expected.
A workaround would be to use the Oracle specific setFixedCHAR method (but it's better to change the datatype to varchar if possible).
The following is from Oracle's PreparedStatement JavaDoc:
CHAR data in the database is padded to the column width. This leads to a limitation in using the setCHAR() method to bind character data into the WHERE clause of a SELECT statement--the character data in the WHERE clause must also be padded to the column width to produce a match in the SELECT statement. This is especially troublesome if you do not know the column width.
setFixedCHAR() remedies this. This method executes a non-padded comparison.
Notes:
Remember to cast your prepared statement object to OraclePreparedStatement to use the setFixedCHAR() method.
There is no need to use setFixedCHAR() for an INSERT statement. The database always automatically pads the data to the column width as it inserts it.
The following example demonstrates the difference between the setString(), setCHAR() and setFixedCHAR() methods.
// Schema is : create table my_table (col1 char(10));
// insert into my_table values ('JDBC');
PreparedStatement pstmt = conn.prepareStatement
("select count() from my_table where col1 = ?");
ResultSet rs;
pstmt.setString (1, "JDBC"); // Set the Bind Value
rs = pstmt.executeQuery(); // This does not match any row
// ... do something with rs
CHAR ch = new CHAR("JDBC ", null);
((OraclePreparedStatement)pstmt).setCHAR(1, ch); // Pad it to 10 bytes
rs = pstmt.executeQuery(); // This matches one row
// ... do something with rs
((OraclePreparedStatement)pstmt).setFixedCHAR(1, "JDBC");
rs = pstmt.executeQuery(); // This matches one row
// ... do something with rs

Categories

Resources