I have a problem with prepareStatement in my projectThe problem is that i want to query tables according to the type of user i.e if user is general then access userlist table and if user is administrator then access admin table
I have tried like :
String userid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
String check = request.getParameter("radio");
String table;
String status="";
if(check.equals("General"))
table="userlist";
else
table="Administrator";
try{
String sql = "Select status from"+table+"where userid=? and pwd=?";
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/Quiz?","root","password");
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,userid);
ps.setString(2,pwd);
ResultSet rs=ps.executeQuery();
I get following exception :
Errorcom.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
'userid='nawed13593' and pwd='hello'' at line 1
I dont want to use createStatement because that will make my project prone to sql injection
Can anyone please help me solve this and the reason why the above exception was thrown?
Thank you in advance
You don't have any spaces before or after your table name. You will wind up with this, in the "Administrator" case:
Select status fromAdministratorwhere userid=? and pwd=?
Insert spaces into your SQL statement string:
// v v
String sql = "Select status from "+table+" where userid=? and pwd=?";
Related
I need help with my college's project(Java web with hibernate and oracle database), this has to edit the users already added previously which have:
Mail pk
pass
typeuser.iduser FK.
add and remove it works but doesnt edit, the error is :
javax.servlet.ServletException: java.sql.SQLSyntaxErrorException: ORA-04054: database link GMAIL.COM does not exist
i already tried with using prepared statement but i think i did it wrong
the mail does not need to be edited. only the type of user and password needs it but at the moment of pressing the edit button it shows me the error gmail.com does not exist
<%
//CONECTANOD A LA BASE DE DATOS:
Class.forName("oracle.jdbc.OracleDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "C##PORTA", "oracle");
String id = request.getParameter("correo");
PreparedStatement stm = con.prepareStatement(id);
String Query = "select * from usuario where correo=" + id;
PreparedStatement ps;
ResultSet rs = stm.executeQuery(Query);
while (rs.next()) {
%>```
OldProgrammer has shown you the correct way to do this. If you use a PreparedStatement (correctly) it will deal with quoting correctly, and also protect against SQL injection attacks.
The reason you got the obscure error message was that your SQL statement most likely looks something like this after you concatenated it:
select * from usuario where correo=someone#gmail.com
Since the email address is not quoted, the SQL parser doesn't recognize that as a string literal. Instead, it is treating it as a "db link" as described in CREATE DATABASE LINK.
After you have created a database link, you can use it in SQL statements to refer to tables and views on the other database by appending #dblink to the table or view name.
And that fails because no such database link with the name "gmail.com" has been created.
You are not calling the correct methods with the correct parameters. Should be something like:
String id = request.getParameter("correo");
String query = "select * from usuario where correo= ?";
PreparedStatement stm = con.prepareStatement(query);
stm.setString(1, id );
ResultSet rs = stm.executeQuery();
I have the following code
try{
sql = "Select Time, Text WHERE Sender =?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "ABC");
rs = stmt.executeQuery();
}catch(SQLException){
System.out.println(e.getMessage());
}
And get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE Sender ='ABC'' at line 1
There is an extra ' in my SQL query, how can I fix that?
It's not the "extra" ' that's the issue. You actually need that for your DB to understand the text you're providing.
The issue is that you're issuing a SELECT statement that is requesting fields from a table which you have not specified. You need to add the table name:
Select Time, Text FROM <tablename here> WHERE Sender =?
Edit: Apparently MariaDB doesn't consider time and text as reserved words as #Andreas pointed out in a comment on this answer.
here is the jsp code which tries to fetch password from a table
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:dsn2");
String U=(String)session.getAttribute("uname");
String query="select pwd from img_pwd where uname='"+U+"'";
Statement s=con.createStatement();
ResultSet r= s.executeQuery(query);
String pas="";
if(r.next())
{
pas=r.getString(2);
}
con.close();
and the table "img_pwd" in the database goes like this--
(uname,nvarchar(50)
(pwd,nvarchar(20))
Hence as described in the question title, i get the error--java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index
NOTE: i have come to know that there is a problem with my resultset code but i am unable to figure it out.
Can anybody Guide me???
Thanks.
Your SQL is selecting one field:
String query="select pwd from img_pwd where uname='"+U+"'";
But this line is looking for field #2 (and you're only SELECTing one).
pas=r.getString(2);
Change it to this, instead:
pas=r.getString(1);
For reference, here is the Java doc on the ResultSet interface's getString method.
Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.
Parameters:
columnIndex - the first column is 1, the second is 2, ...
I am having some trouble with, what I believe to by syntax, for prepared statements.
I have the following code
String query2="SELECT lname FROM school_student WHERE sid = ? ORDER BY sid;";
PreparedStatement ps = cn.prepareStatement(query2);
ps.setInt(1, 3);
ResultSet rs = ps.executeQuery(query2);
The problem I am having is that I am getting this error message:
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 '? ORDER BY sid' at line 1
However, when I substitute the "?" in my query for a 3, the query works fine with no error and gives me what I want. There seems to be something wrong with how I am setting the value of the "?" in my query? Am I using the wrong syntax?
Simply use
ps.executeQuery();
(i.e. use the overloaded executeQuery() method which doesn't take any argument). You already passed the query when preparing the statement.
use this query :-
String query2 = "SELECT lname FROM school_student WHERE sid =
"+attribute+" ORDER BY sid;";
and simply use
ps.executeQuery();
I think their is syntax problem while preparing query
try this one...
String query2="SELECT lname FROM school_student WHERE sid = +variablename+ ORDER BY sid;"
I'm trying to connect netbeans to my postgresql database. The connection seems to have worked as I don't get any errors or exceptions when just connecting, methods such as getCatalog() also return the correct answers.
But when I try to run a simple SQL statement I get the error "ERROR: relation "TABLE_NAME" does not exist", where TABLE_NAME is any one of my tables which DO exist in the database. Here's my code:
Statement stmt = con.createStatement();
ResultSet rs;
String query = "SELECT * FROM clients";
rs = stmt.executeQuery(query);
I was thinking that netbeans might not be finding the tables because it's not looking in the default schema (public), is there a way of setting the schema in java?
EDIT: My connection code. The database name is Cinemax, when I leave out the statement code, I get no errors.
String url = "jdbc:postgresql://localhost:5432/Cinemax";
try{
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException cnfe) {
System.err.println("Couldn't find driver class:");
cnfe.printStackTrace();
}
Connection con = DriverManager.getConnection( url,"postgres","desertrose147");
I suspect you created the table using double quotes using e.g. "Clients" or some other combination of upper/lowercase characters and therefor the table name is case sensitive now.
What does the statement
SELECT table_schema, table_name
FROM information_schema.tables
WHERE lower(table_name) = 'clients'
return?
If the table name that is returned is not lowercase you have to use double quotes when referring to it, something like this:
String query = "SELECT * FROM \"Clients\"";
You could check these possibilities:
String query = "SELECT * FROM clients";
String query = "SELECT * FROM CLIENTS";
String query = "SELECT * FROM \"clients\"";
String query = "SELECT * FROM \"CLIENTS\"";
String query = "SELECT * FROM Clients";
Maybe one of those would work.
Besides CoolBeans' suggestion, you may also be connecting to the db as a different user who does not have permission on the relevant db or schema. Can you show the connection string?
Funny thing is i was experiencing the same thing as i had just started on netbeans and postgressql db, and the error was fixed after noting that the issue was that my tables in postgressql had capital letters in my naming convention which me and my jdbc query statement for INSERT was failing to find the table. But after renaming my tables in the db and fixing the column names as well am good to go. Hope it helps.