SQL command not properly ended in servlets - java

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
}

Related

Java Login Form somehow skips if-else statement

I am trying to create a Login and Register form using Java and SQL Workbench. The Register form works properly as the Username and Password are added to the SQL Database. As for the Login form, everything looks fine. But, when it is executed, it skips the If Statement and goes straight to the Else Statement. The Username and Password are correct as I checked the SQL Database table. The output is a SqlSyntaxErrorException. Therefore, I think my syntax is wrong. Any help would be highly appreciated!
This is the code below:
if (e.getSource() == LOG_IN_BUTTON)
{
String userName = USER_NAME_TEXTFIELD.getText();
String password = PASSWORD_TEXTFIELD.getText();
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/airline_connect",
"root", "Yasser1595");
String sql = "Select user_name, password from account where user_name=? and password=?";
st = connection.prepareStatement(sql);
st.setString(1, userName);
st.setString(2, password);
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
frame.dispose();
new MainGame();
JOptionPane.showMessageDialog(LOG_IN_BUTTON, "You have successfully logged in");
} else {
JOptionPane.showMessageDialog(LOG_IN_BUTTON, "Wrong Username & Password");
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
Try the following,
ResultSet rs = st.executeQuery();
Don't pass the sql string to executeQuery. When you pass the sql string to executeQuery it considers it as plain text instead of prepared statement
You did not use PreparedStatement.executeQuery() but the parent's Statement.executeQuery(sql) which is a known pitfall. Also it is worth using try-with-resources with local variables. Not closing things can cause resource leaks.
String sql = "select user_name, password from account where user_name=? and password=?";
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/airline_connect",
"root", "Yasser1595");
PreparedStatement st = connection.prepareStatement(sql)) {
st.setString(1, userName);
st.setString(2, password);
try (ResultSet rs = st.executeQuery()) { // No sql parameter.
if (rs.next()) {
frame.dispose();
new MainGame();
JOptionPane.showMessageDialog(LOG_IN_BUTTON, "You have successfully logged in");
return;
}
JOptionPane.showMessageDialog(LOG_IN_BUTTON, "Wrong Username & Password");
}
} catch (SQLException exc) {
exc.printStackTrace();
}
It still did not work
PASSWORD also is a function, but as no syntax errors happend, that probably is no problem. You might try "password" (= column name).
The column might store not the password - which is a security risk, should
the database be stolen in the future. It might store some hash of the password.
So:
String sql = "SELECT user_name, \"password\" "
+ "FROM account "
+ "WHERE user_name=? AND \"password\"=PASSWORD(?)";
First check how passwords (or their hashes) are stored.
It might also be the case that the password handling is done at the java side, for instance by taking the MD5 of the password and storing that.
Should all work, consider an other securite measure: if the password field is a JPasswordField one should ideally not work with a String, but a char[] that can be wiped out after usage (Arrays.setAll(pwdArray, ' ');). A String could reside long in memory, which might be a security risk.

Select statement in Java terminates with an error

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
}

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

Update sql statement in servlet not in servlet

I am trying to allow the user to change the password if he enters the right username. The username is drawn from the database and compared to the username the user enter in a form. My problem is after the validation is done the UPDATE statement is not producing any result. Can someone help me out please?
String un = request.getParameter("username");
String psw = request.getParameter("password");
String cPsw = request.getParameter("cpassword");
Connection con = ConnectionHelper.getConnection();
try {
ResultSet rs = userList(con);
if (rs.next()) {
String n = rs.getString("username");
if (n.equals(un)) {
out.print("Password match");
String updateQuery = "UPDATE RegisteredUserInfo SET password ='"
+ cPsw + "'WHERE username ='" + un + "'";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.executeQuery();
ServletContext context = getServletContext();
RequestDispatcher rd = context
.getRequestDispatcher("/Welcome.jsp");
rd.forward(request, response);
}
}
} catch (SQLException sx) {
out.println();
}
}
public ResultSet userList(Connection con) throws SQLException {
PreparedStatement ps;
ResultSet rs;
String matchingUname = "SELECT username FROM RegisteredUserInfo";
ps = con.prepareStatement(matchingUname);
rs = ps.executeQuery();
return rs;`
Try with ps1.execute(); or ps1.executeUpdate() instead of ps1.executeQuery();
Call con.commit(); to commit the changes and Don't forget to close the resources in the end.
Check the return type of below methods to make sure that data is inserted properly.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Ream more about Difference between execute, executeQuery, executeUpdate
Points to Remember
Use PreparedStatement instead of using single quoted query string that may cause issue. Find a sample on Using Prepared Statements
Don't forget to close the resources such as connection, result set and statement.
Use finally block to handle it or Read more about Java7 -The try-with-resources Statement
Don't simply eat the exception in catch block. Do proper handling of the exception. You can try with e.printStackTrace() while development.
You need to call executeUpdate() for SQL UPDATE (or INSERT/DELETE).
String updateQuery = "UPDATE RegisteredUserInfo SET password = ?"
+ " WHERE username = ?";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.setString(1, cPsw);
ps1.setString(2, un);
ps1.executeUpdate();
Also use the PreparedStatement as above. Look for SQL Injection, also escapes '.

Quoted string not properly terminated Exception

I was updating password in an oracle databse using a java servlet like this
Connection con;
PreparedStatement ps,ps1;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e)
{
System.out.println("Drivers Not Found");
}
try{
con=DriverManager.getConnection("jdbc:odbc:SharedCryptography", "fyp", "fyp");
}catch(SQLException e1)
{
}
String query="UPDATE tbGroup SET GPassword='"+mypassword+"' where GName='"+GroupNamee+"' and OEmail='"+OwnerId+"'";
java.sql.Statement stmt = con.createStatement();
stmt.executeUpdate(query);
But it gives java.sql.SQLException: [Oracle][ODBC][Ora]ORA-01756: quoted string not properly terminated
Am i doing something wrong in it?Please help
You should absolutely avoid string concatenation in SQL statements. You will get in all kind of security and stability problems. Your problem is simply be resolved by using a prepared statement:
String sql="UPDATE tbGroup SET GPassword=? where GName=? and OEmail=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, myPassword);
ps.setString(2, groupName);
ps.setString(3, ownerId);
ps.executeUpdate();
If you do this, no "'" or "%" or "_" or " in your parameters will cause any problems. Alternatively you can try to escape your characters, but why bother - the PS method is not only more robust and easier to read, it is often also more performant.
For a general description of the security problems, see: https://www.owasp.org/index.php/SQL_injection
One of your variables (probably password) has a quote or semi colon in it. Since you build up your query via String concatenation, you are vulnerable to SQL injection attacks. It looks like you accidentally attacked yourself via injection. If you had a properly maliciously formatted variables you could have done quite a bit of damage to your database.
Please use Parameterized queries
PreparedStatement stmt = con.prepareStatement("UPDATE tbGroup SET GPassword= ? where GName= ? and OEmail=?" )
stmt.setString(1, mypassword);
...
stmt.executeUpdate();
See this for more details
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java

Categories