Select statement in Java terminates with an error - java

As I'm finding my way slowly in Java , I'm facing a runtime error when my program is executed..
I'm doing this coding in a select statement …
i get an error code that using "?" this way is not accept in MariaDB syntax!!
How to solve this issue ….
note that UserName is defined as avariable in the prog.
Thanks
Here's my Code:
String sql = "select Username , Userpassword from Users where Username where Username = ?";
statement = con.prepareStatement(sql);
statement.setString(1, UserName);
statement.executeQuery(sql);
while (statement.getResultSet().next()){
// ...

where Username where Username = ?
Your SQL query is invalid. You have a where clause twice.

Your code has two problems that I can see. First, as #Michael pointed out, you have two WHERE clauses. Maybe this is just a copying error, or maybe this is verbatim what your code is. In either case, it's wrong, and your query should have just one WHERE clause. The other problem is that you are making the following call to execute the query:
statement.executeQuery(sql);
PreparedStatement#executeQuery does not take any parameters; just call it with no parameters. So here is the suggestion I would make for you:
String sql = "SELECT Username, Userpassword FROM Users WHERE Username = ?";
statement = con.prepareStatement(sql);
statement.setString(1, UserName);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
// process a row
}

Related

How to pass JSP parameters to a SQL query?

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.

i am trying to get id from table name data base to stor in variable so i can use in another table it give sql syntax error

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+"%'");

Getting an error in createStatement

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).

SQL command not properly ended in servlets

i have a servlet which takes emailid and password from a form, which is then supposed to access the table called hr.faculty, and if the credentials found correct, creates a session. but i am getting an error: java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended when i try to login. plz help.
The code is as follows:
email=request.getParameter("email");
pass=request.getParameter("pass");
try{
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
out.println(ex);
}
Connection con=null;
con=DriverManager.getConnection(oracleURL,username,password);
DatabaseMetaData dmd=con.getMetaData();
Statement s=con.createStatement();
String q="SELECT password FROM HR.faculty WHERE email=" + email;
ResultSet rs=s.executeQuery(q);
pw=rs.getString("password");
if(pw.equals(pass)){
//session creation
}
Looks like a syntax error on your query, you're not using binding variables so you have to do the wrapping yourself. This would work:
String q="SELECT password FROM HR.faculty WHERE email='" + email+"'";
In general using prepared statements is much preferred as it protects you from SQL injection.
Also looks like your retrieval of the result is invalid, you need to move the cursor in the ResultSet otherwise it will return an error. This would work:
ResultSet rs=s.executeQuery(q);
rs.first();//move to the first result
pw=rs.getString("password");
Try
String q="SELECT password FROM HR.faculty WHERE email='" + email + "'";
But you look for prepared statements.
I kind of cringe every time I see code like this. You should be using prepared Statements instead. What you are doing allows SQL injection.
It will alleviate the security holes, and your syntax error if you use prepared statements.
Use PreparedStatment s = con.prepareStatement(mySqlQuery); instead of Statement s = con.createStatement();
Then in your sql string, you replace all "input" with a ?, so mySqlQuey = "SELECT password FROM HR.faculty WHERE email=?"
You then replace all question marks with s.setString(1, value). Or if you were replacing it with an int it would be s.setInt(1, value); etc.
The edit to your code:
Connection con=null;
con=DriverManager.getConnection(oracleURL,username,password);
DatabaseMetaData dmd=con.getMetaData();
PreparedStatement s=con.prepareStatement("SELECT password FROM HR.faculty WHERE email=?");
s.setString(1, email);
ResultSet rs=s.executeQuery(q);
pw=rs.getString("password");
if(pw.equals(pass)){
//session creation
}

How to change table name of from clause in PreparedStatement

Hi i have a small problem, how do i switch tables to get results from??
The code below is not working.However that should give you some idea of what i am trying to do.
Thanks for the help
String typelogin=null;
if(xx){
typelogin="users_table";
}else{
typelogin="admin_table";
}
String sqlStr = "Select * from "+typelogin+" where username=? and userpassword=?";
PreparedStatement stmt = conn.prepareStatement(sqlStr);
The full code:
Statement stmt = conn.createStatement();
String sqlStr = "Select * from "+typelogin+" where username=? and userpassword=?";
PreparedStatement pstmt=conn.prepareStatement(sqlStr);
pstmt.setString(1,user);
pstmt.setString(2,password);
//step 6 Process result
ResultSet rs = pstmt.executeQuery();
The error i am getting:
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 'fromspmovy_admin where username='abc' and userpassword='abc'' at line 1
Answer[SOLVED]:
forgot to put white space
from " + typelogin + " where
From your error message: 'fromspmovy_admin where ... looks like you missed a whitespace between from and your table name. Make sure you're doing this in the right way in all your methods (note that in your current example this won't happen).
If you will use ? for pass the variables, you must use PreparedStatement not Statement. Also according your error message you need to add a white space after from (check fromspmovy_admin)

Categories