I want to write a SQL query which contains parameters from a JSP.
I tried it like this
String sqlstring = "\"select"+Activity+" from backgroundcost where onpremprice =' "
+service+" '\"";
PreparedStatement ps = con.prepareStatement(sqlstring);
ResultSet rs = ps.executeQuery();
I'm getting an error.
First of all, I hope you mean that service is a variable that comes from a form of your JSP, that this variable ends up in your Controller and that your controller delegates the access to the database layer to another class.
There are multiple problems with your request :
You use quotes inside your SQL query, you shouldn't.
What is Activity ? probably you miss a space character between ´select´ and the value of `Activity´
The goal of a ´PreparedStatement` is to avoid SQL Injection. You MUST use the code i show below instead of your parameter directly injected in your built SQL statement.
Consider using StringBuilderif you have multiple String concatenations
"
String sqlstring = "select activity from backgroundcost where onpremprice = ?";
PreparedStatement ps = con.prepareStatement(sqlstring);
ps.setString(1, service);
ResultSet rs = ps.executeQuery();
Don't is the short answer. It is a bad design to have database logic in your view. Pass the params from your jsp to a backend java bean en let that fill in the query
make it like this..
String sqlstring = "select * from backgroundcost where onpremprice ='"+service+" '";
PreparedStatement ps = con.prepareStatement(sqlstring);
ResultSet rs = ps.executeQuery();
// in place of * you can put the column name that u need to be selected.
Related
here is the code there is catch close but i delete it so can anyone replay to me
String id = null;
String root="root",student="root";
String name=jTextField1.getText();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection
con=(Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306
/dijlafinal1",root,student);
String query2="SELECT * FROM name WHERE name like ? ";
PreparedStatement pstm2=null;
pstm2=con.prepareStatement(query2);
pstm2.setString(1,"%"+name+"%");
ResultSet rs = pstm2.executeQuery(query2 );
while (rs.first()){
String name1=rs.getString("name");
id= rs.getString("id");
int epo =rs.getInt("epo");
}
jTextField2.setText(id);
}
You need to use the no-argument version of executeQuery(), i.e.
ResultSet rs = pstm2.executeQuery();
The reason is that you've already prepared the statement when you called con.prepareStatement(query2). Calling executeQuery(query2) will throw away the prepared SQL and execute the query without bind variables, leaving the ? in place -- as the error message suggests.
When working with a PreparedStatement you always call the .execute... methods without any arguments because you have already supplied the SQL command text with the .prepareStatement call. So
ResultSet rs = pstm2.executeQuery(query2 );
is incorrect. You need to simply do
ResultSet rs = pstm2.executeQuery();
I wonder if it might work if you use this?
pstm2.setString(1,"'%"+name+"%'");
When I use the following code it runs perfectly.
PreparedStatement st = con.prepareStatement("select * from users where username=?");
st.setString(1, userId);
ResultSet rs = st.executeQuery();
But when I am using the following code, I get an error that userId (that I pass as parameter) is an invalid column name.
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where username="+userId);
Why statement method doesn't work and I have to use PreparedStatement?
User ID is a string (SQL calls this type CHAR or VARCHAR), it must be put in quotes if used in the SQL requests. Like this:
select * from users where username='12345'
PreparedStatement is much better solution because of the SQL injection. You CANNOT just write:
ResultSet rs = st.executeQuery("select * from users where username=\""+userId+"\"");
WRONG CODE - ^^^^^^^^^^^^^^^
because user ID can contains control characters like ['], ["] or [\]. It depends on the SQL server and sometimes are more sophisticated than it looks like. If using PreparedStatement, it is automatically managed by the JDBC driver.
First of all, is better to use the first one. But if you really want to use the second one, you need to put your value into quotes. Simple add the quotes to the value. But is good to create a function to it, if you are going to use it a loot. Like:
public String doubleQuoted(String value){
return "\"" + value + "\"";
}
or
public String singleQuoted(String value){
return "'" + value + "'";
}
and use
ResultSet rs = st.executeQuery("select * from users where username="+singleQuoted(userId));
You need to put strings into quotes:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where username=\'"+userId+"\'");
\ is the escape character.
Note:
Your prepared statement is the preferred way of handling SQL queries. See #30thh answer as to why (SQL Injection attacks).
How do I set Dynamic query parameters in Apache drill. I tried and received error message saying: java.sql.SQLFeatureNotSupportedException:
Prepared-statement dynamic parameters are not supported.
Is it true that drill does not support such a feature, as in:
String sql = "select employee_id,first_name,last_name from dfs.'employee.json' where id = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, 23);
ResultSet rs = preparedStatement.executeQuery(sql);
Can any one please suggest a work around for this, if there's any
As of now, this support is not there. Drill does not support Prepared-statement dynamic parameters.If still some one wants to go ahead with such dynamic parametres for their queries, they would have to set using statements this way:
Statement statement = connection.createStatement();
String queryParam = "Computers"
String sqlQuery = "select employee_id,first_name,last_name from dfs.'employee.json' where department LIKE'" +queryParam +"'"+"and conditions<...> ";
ResultSet rs = statement.executeQuery(sqlQuery);
while(rs.next)
{
do as you need
}
My code goes something like this
DataBaseUtil dbBaseUtil=new DataBaseUtil();
Connection con=dbBaseUtil.getConnection();
String query="select case_id, ticket_id from VAPP_ITEM where
(person1_alt_email='" + username +"') and ticket_type='Service Request' and ticket_status not in ('Closed','Resolved')";
ResultSet rs=dbBaseUtil.getDbResultSet(query);
List<String> tickets=new ArrayList<String>();
while(rs.next())
ticket.add(rs.getString("case_Id")+"-"+rs.getString("ticket_Id"));
MyTicketUtil.searchAndOpenTicket(webui, "", tickets.get(0));
Now, once I get the element "tickets(0)", I perform some operations on it, and after the operations are performed, I need to retrieve ticket_status for the ticket on which the operations were performed - tickets(0).
However, to query the database, I need case_id and ticket_id for tickets(0). How can it be done?
I tried creating two ResultSets and a query post operations like below:
while(rs1.next())
quer1 = "select ticket_status from VAPP_ITEM where case_id=rs.getString(1) and ticket_id = rs.getString(2)";
But this is not working - console shows below error:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot find either column "rs" or the user-defined function or aggregate "rs.getString", or the name is ambiguous.
You have included rs.getString() into string literal.
You should use PreparedStatement for such things:
quer1 = "SELECT ticket_status FROM vapp_item WHERE case_id=? AND ticket_id = ?";
PreparedStatement pstm = conn.prepareStatement(quer1);
while (rs1.next())
{
pstm.setString(1, rs.getString(1));
pstm.setString(2, rs.getString(2));
rs2 = pstm.executeQuery();
...
}
I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;
Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.