I've been trying to make a login page and have run into a problem with pulling information from the database containing User credentials. When running the code I get the following error "Error: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=USERNAME, DRIVER=3.68.61" meaning (I think) that the column username cannot be located, but it is there. The table USERS contains the columns username, password, f_name, and l_name. The username and password for this application are collected via a JSP and passed to a servlet which in turn calls the following .java which has been passed both the username and password entered by the user:
public class Database {
public String lookup( String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
String f_name = "";
String query = "SELECT f_name FROM USERS WHERE username = ? AND password = ?";
try
{
System.out.println("Connecting to Database");
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection("jdbc:db2://ipaddress:port/database name", "username", "userpassword");
System.out.println("Connection Successful");
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
resultset = statement.executeQuery();
if( resultset.next())
{
f_name = resultset.getString("f_name");
}
}
catch(ClassNotFoundException error)
{
System.out.println("Error: " + error.getMessage());
}
catch ( SQLException error)
{
System.out.println("Error: " + error.getMessage());
}
finally
{
if( connection != null)
{
connection.close();
}
if( statement != null)
{
statement.close();
}
if( resultset != null)
{
resultset.close();
}
}//end finally
return f_name;
}
}
Any ideas on what is going on?
42703 means An undefined column, attribute, or parameter name was detected.
Here is the link with different DB2 error codes https://urssanj00.wordpress.com/2008/03/04/db2-sql-error-code-and-description/
Could that be that you created your columns in lowercase? Try select colname from syscat.columns where tabname = 'USERS'. If the columns show in lowercase you'd have to quote them in every query: select "f_name" from users where "username" = 'whatever'.
Related
Is there a way to pass data values for a MySQL database into a variable in Java?
This is what I have tried so far:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Login", "root", "****");
String query = "Select username, passphrase from student where username=?";
statement = connection.prepareStatement(query);
resultSet = statement.executeQuery(query);
if (resultSet.next()) {
_name = resultSet.getString(2);
_pass_phrase = resultSet.getString(3);
}
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
assert resultSet != null;
resultSet.close();
statement.close();
}
but I keep on getting a NullPointerException that points to my _name variable, telling me it empty. Could someone please point out to me what it is doing, and how to correct it?
code in update button
String password = new String(oldPass.getPassword());
String newPassword = new String(newPass.getPassword());
String realpass = zz.getText();
String us = z.getText();
if(password.equals(realpass))
{
System.out.println("ok");
String query = "UPDATE user SET password = '"+newPassword+"' WHERE username = '"+us+"'";
try{
Statement st = (Statement) con.prepareStatement(query);
int i = st.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null, "Ooopps! I guess you should call your programmer. ^^");
}
}catch(Exception e){
System.out.println(e);
}
}
code in log in
Methods m = new Methods();
String pass = new String (password.getPassword());
String user = username.getText();
if(m.logInUser(user, pass)==true){
form2 f = new form2();
f.setUser(user);
f.setPass(pass);
f.setVisible(true);
this.dispose();
}....and so on....
code for method log in user
public boolean logInUser(String user, String pass){ //true = nakarecord na sa database login form
try{
String query = "Select * from user where username = ? && password = aes_encrypt('"+pass+"', 'nicanor')";
PreparedStatement pst = (PreparedStatement) con.prepareStatement(query);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
if(rs.next()){
return true;
}
else{
return false;
}
}
catch(Exception e){
System.out.println(e);
return false;
}
}//logInUser
it says successfully connected in sql and the database is updated but i cant see the next form that should pop up after i entered the updated password
There are few problems with your code:
(1) In your update() logic, you are using the mix of PreparedStatement and Statement together, rather use always use PreparedStatement to bind the input parameters, otherwise they (statements/queries) are prone to SQL injection attacks.
You can refer the below code with inline comments to bind the input parameters with PreparedStatement:
//Write the SQL query with ? to bind the parameters in PreparedStatement
String query = "UPDATE user SET password = ? WHERE username = ?";
PreparedStatement pstmt = null;
try{
//create the PreparedStatement object
pstmt = con.prepareStatement(query);
//bind the input parameters using setString()
pstmt.setString(1, newPassword);
pstmt.setString(2, us);
//execute the prepare statement now
int i = pstmt.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password
is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null,
"Ooopps! I guess you should call your programmer. ^^");
}
} catch(Exception e){
System.out.println(e);
} finally {
if(pstmt != null)
pstmt.close();
if(con != null)
con.close();
}
Also, remember that database resources are costly and you need to close the resources in the finally block as shown above, otherwise you will end up with resource leaks.
(2) In your logInUser() logic, you are using && which is incorrect, rather in sql you need to use AND operator as shown below:
String query = "Select * from user where username = ?
AND password = aes_encrypt('"+pass+"', 'nicanor')";
I am trying to check if a user entered Username and password matches one in my data base however what ever I try the result set still comes up null. the sql varible is set to the username and the pass is set to the password however when ever i enter the correct details it shows up with no results
public boolean Login(){
boolean valid = true;
try {
String stmt = "SELECT * From TBLUser where User = ? and Password = ? ;";
PreparedStatement pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, sql); pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if(!rs.next()){
valid = false;
}
} catch (SQLException e) {
System.err.println("Error: "+e);
}
return valid;
}
Also, better practice:
public boolean Login(String asql, String apass){
boolean valid = true;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String stmt = "SELECT * From TBLUser where User = ? and Password = ? ";
pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, asql);
pstmt.setString(2, apass);
rs = pstmt.executeQuery();
valid = (!rs.next());
} catch (SQLException e) {
e.printStaceTrace();
} finally { // cleanup
try { rs.close(); } catch (Exception ex) {}
try { ps.close(); } catch (Exception ex) {}
}
return valid;
}
Use unit cap with " " to save your column-Table like
Create Table "TBLUser"{
"User" char...
"Password"...
}
similarly, your select query will change String
stmt = "SELECT * From \"TBLUser\" where \"User\" = ? and \"Password\" = ? "
This should work.
The problem with the application is not the code but the database as User one of the column names is a reserved word so this change fixed the problem thanks to #Grayson for all the help
public boolean Login(){
boolean valid = true;
try {
String stmt = "SELECT * From TBLUser where UserName = ? and Password = ? ;";
PreparedStatement pstmt = conn.prepareStatement(stmt);
pstmt.setString(1, sql); pstmt.setString(2, pass);
ResultSet rs = pstmt.executeQuery();
if(!rs.next()){
valid = false;
}
} catch (SQLException e) {
System.err.println("Error: "+e);
}
return valid;
}
I'm developing login application using java servlet and mysql and I'm getting following error when I'm trying to login by giving username and password.
java.sql.SQLException: Column 'alex' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.ResultSet.findColumn(ResultSet.java:987)
at com.mysql.jdbc.ResultSet.getString(ResultSet.java:5584)
at org.kaveen.login.database.LoginDaoImpl.userValidate(LoginDaoImpl.java:36)
at org.kaveen.login.controller.Login.doPost(Login.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
..................................
This is my LoginDaoImpl class
public class LoginDaoImpl implements LoginDao {
public String userValidate(LoginBean loginBean) {
String userName = loginBean.getUserName();
String password = loginBean.getPassword();
System.out.println(userName);
System.out.println(password);
String sql = "select username,password from users";
String userNameDB = "";
String userPasswordDb = "";
Connection connection = null;
java.sql.Statement statement = null;
ResultSet resultSet = null;
try {
connection = DbConnecton.setConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
userNameDB = resultSet.getString(userName);
userPasswordDb = resultSet.getNString(password);
if (userName.equals(userNameDB)
&& password.equals(userPasswordDb)) {
return "Success";
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return "Failed invalid credentials";
}
}
Can any one please explain why I'm getting this error? and how can I fix it?.
You are trying to login with a username called "alex"? here is your error:
userNameDB = resultSet.getString(userName);
When using the method getString on a ResultSet you can specify the column index (starting from 1) of the column in the result, or the column name (in your case the column name is "username"). You are passing the actual username to the method and of course that column does not exist.
try this:
userNameDB = resultSet.getString("username");
What your are doing is very wrong. your query gets all the rows from users table and your are iterating over it.
to correct it you have to pass the name of the column when getting data from result set.
userNameDB = resultSet.getString(userNameColumn);
userPasswordDb = resultSet.getNString(passwordColumn);
but this way is very stupid. you can do this in your database with a simple query.
with this query there is no need for iteration.
select * from users where username_col=username and password_col=password
assuming that you store passwords in raw text which is wrong.
You should prepare a single SQL query to check if your user credentials are matching, looping over a result set can be costly (when number of user is high).
String sql = "select username, password from users where username=:username and password = :pass";
Connection connection = null;
java.sql.Statement statement = null;
ResultSet resultSet = null;
try {
connection = DbConnecton.setConnection();
statement = connection.createStatement();
resultSet= statement.executeQuery(sql);
resultSet.setString("username", username );
resultSet.setString("pass", password );
if (resultSet.hasNext()){ // check if we had found someone with same username and password
return "Success";
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(connection!=null)// finaly remember to close connection if open
connection.close()
}
return "Failed invalid credentials";
I have a database table with the following layout:
Columns:
_________________________
id | user_name | password
But I can't delete a specified row by using the username.
I am receiving the following error:
MySQLSyntaxErrorException: Unknown column 'vipin' in 'where clause'
vipin is a value within the table.
Can anyone help me?
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username = removeText.getText();
ArrayList<String> values = new ArrayList();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
values.add(0, rs.getString(("user_name")));
System.out.println(values);
}
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
if (values.contains(username)) {
username = removeText.getText();
Boolean isAdmin = false;
try {
System.out.println(username);
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE user_name=" + username + "");
preparedStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
Util.showErrorMessageDialog(username + " is not found.Please try again.");
}
}
Since you're already using PreparedStatement, use it right and pass the username as parameter instead of just concatenating the Strings:
//no need to use a cast here
preparedStatement = connection.prepareStatement(
//note the usage of ? instead of concatenating Strings
"DELETE FROM users WHERE user_name=?");
//setting the first parameter in the query string to be username
preparedStatement.setString(1, username);
preparedStatement.executeUpdate();
Using this, you won't have any concatenation problems and what's better, your code won't be prone to SQL Injection.
Not directly related to your problem, but it would be better if you move the code to execute INSERT, UPDATE and DELETE statements to a single method.
public void executeUpdate(Connection con, String query, Object ... params)
throws SQLException {
PreparedStatement pstmt = con.prepareStatement(query);
if (params != null) {
int i = 1;
for(Object param : params) {
pstmt.setObject(i++, param);
}
}
pstmt.executeUpdate();
pstmt.close();
}
So your code would be dramatically reduced to:
String deleteSQL = "DELETE FROM users WHERE user_name=?";
executeUpdate(deleteSQL, username);
Note that you can create a new method based on this approach to execute SELECT statements.
Also, don't forget to close your resources. This also can be dramatically reduced using a method like this:
public void closeResource(AutoCloseable res) {
try {
if (res != null) {
res.close();
}
} catch (Exception e) {
//handle this exception...
//basic example, not meant to be used in production!
e.printStacktrace(System.out);
}
}
Note that Connection, Statement (and its children PreparedStatement and CallableStatement) and ResultSet interfaces already extend from AutoCloseable.
You haven't quoted the username you're inserting into the query, so it's being treated as a reference to a field name:
DELETE FROM users WHERE user_name='"+username+"'"
^-- ^--
Note: building queries like this leaves you open to SQL injection attacks. Used prepared statements and placeholders instead.
I think you might need some quotes round the username in the where clause
connection.prepareStatement("DELETE FROM users WHERE user_name='"+username+"'");
You are going to want to quote your Strings
"DELETE FROM users WHERE user_name="+username+"";
Like this:
"DELETE FROM users WHERE user_name='" + username + "'";
What would be better is just using PreparedStatement as it was intended:
"DELETE FROM users WHERE user_name = ?";
And then using:
preparedStatement.setString(1, username);
before calling executeUpdate
The query should look like this
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE user_name='"+username+"'");
Note : Mind the single quotes used for user_name='"+username+"'"