PreparedStatement is undefined error in jsp page - java

I am new to jsp pages and trying to make a login page by checking username and password from the database. Here is the code:
protected void CheckUser(String username, String password)
{
try {
connect();
PreparedStatement preparedStatement = con.PreparedStatement(
"SELECT * Users WHERE username = ? AND password = ?");
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
ResultSet rs = (ResultSet) preparedStatement.executeQuery();
} catch (Exception e) {
System.out.println("cannot connect");
e.printStackTrace();
}
}
I get the following error for con.PreparedStatement
The method PreparedStatement(String) is undefined for the type Connection
Can anyone help me with this?
Thanks
Edit: Here is my connection function:
static String dbUrl="jdbc:mysql://localhost:3306/Bank";
static String username="root";
static String password="";
static Connection con=null;
public static void connect ()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=(Connection) DriverManager.getConnection(dbUrl,username,password);
System.out.println("Connected!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("not connected");
}
}

You spelled the method wrong Connection#prepareStatement(String sql) throws SQLException.
It should be con.prepareStatement, not con.PreparedStatement.

You have to create a Prepared Statement by doing PreparedStatement preparedStatement = con.prepareStatement("your Query");
You need the from keyword in your Query.
Hence, your code should look like
PreparedStatement preparedStatement = con.prepareStatement("SELECT * from Users WHERE username = ? AND password = ?");

Not sure about other stuff, but your query is wrong considering its not an typo, will throw SQLException.
It should be
"SELECT * FROM Users WHERE username = ? AND password = ?"
^^^^
||||
here

Related

org.sqlite.SQLiteException: [SQLITE_NOTADB] File opened that is not a database file (file is encrypted or is not a database) [NETBEANS]

So i got this form that I'm using but I get that error whenever i submit, it says CONNECTION SUCCESSFUL but then it returns the error and never insert nor retrieves anything from the db. I checked the version of the sqlite and everything, can't figure it out.
public class databaseConnection {
public static Connection connection = null;
public static Connection getConnection() throws ClassNotFoundException {
try {
System.out.println("CONNECTING");
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:SoftwareDB.db");
System.out.println("CONNECTION SUCCESSFUL");
} catch (SQLException e) {
System.out.println("ERROR: Connection Failed!");
}
return connection;
}
public static void login(String username, String password, String login) throws ClassNotFoundException {
try {
System.out.println("INSERTING");
try (Statement stmt = getConnection().createStatement()) {
String sql = "INSERT INTO login (username, password) VALUES ('" + username + "', '" + password + "', '" + login + "');";
stmt.execute(sql);
}
getConnection().close();
System.out.println("INSERT SUCCESSFUL");
} catch (SQLException ex) {
Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static ResultSet getLoginDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
ps.close();
getConnection().close();
}
return rs;
}
public static ResultSet getExistentDetails(String query) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (PreparedStatement ps = getConnection().prepareStatement(query)) {
rs = ps.executeQuery();
getConnection().close();
}
return rs;
}
}
private void loginBtnMouseClicked(java.awt.event.MouseEvent evt) {
if (username.getText().isEmpty() || password.getText().isEmpty()) {
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} else {
try {
databaseConnection.getLoginDetails("SELECT * FROM register WHERE email = '?' AND password = '?'");
String ts = new SimpleDateFormat("dd.MM.yyyy - HH.mm.ss").format(System.currentTimeMillis());
databaseConnection.login(username.getText(), password.getText(), ts);
JOptionPane.showMessageDialog(null, "Login succesful!");
new login().setVisible(true);
infoLabel.setVisible(true);
username.setText("");
password.setText("");
} catch (HeadlessException ex) {
JOptionPane.showMessageDialog(null, "Failed!");
} catch (SQLException | ClassNotFoundException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Output
I believe you have forgotten an important thing: properly preparing your PreparedStatement and opening/closing connections correctly.
Would you try the following rewritten getLoginDetails() method and take inspiration from it for the other methods?
public static ResultSet getLoginDetails(String query, String email, String password) throws SQLException, ClassNotFoundException {
ResultSet rs;
try (Connection conn = getConnection()) {
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1,email);
ps.SetString(2,password);
rs = ps.executeQuery();
// Do something with the ResultSet here or do not close the statement!
}
}
return rs; // should be something else! (as it could be already closed)
}
Then you certainly need to do something with the ResultSet! For example: check that the email/password combination exists in order to validate the login request.
Also, some important remarks and tips:
better check that the connection is valid after initialization using isValid(timeout)
think about a connection pool or at least some ways to reuse your connection(s)
eventually use existing tools (libraries like Apache) for your ORM (Object-Relation Mapping) and DAO (Database Access Object) layers. Actually, that's highly recommended.
closing a PreparedStatement will automatically close the associated ResultSet. Your code does not take that into account. Cf. https://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html
Keep me posted!

Trying to show info from database into terminal

I'm trying to display a list of the names of people in the database from the terminal, but not sure about how I would go about this. Right now I'm using a prepared statement
public static void showNames() throws SQLException {
Statement stmt=null;
Connection conn=null;
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
String selectTable="SELECT * FROM userInfo;";
stmt.execute(selectTable);
}
You're close.
Below code is not a complete answer, but hopefully enough to get you moving in the direction of obtaining a complete answer. The below code is basically the code you posted with some modifications.
public static void showNames() throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
String selectTable="SELECT * FROM userInfo;";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
rs = stmt.executeQuery(selectTable);
while (rs.next()) {
Object obj = rs.getObject("name of column in database table USERINFO");
System.out.println(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}
You didn't post the structure of database table USERINFO, so replace name of column in database table with the actual column name.
By the way, there are many examples of how to do this on the Internet, for example Processing SQL Statements with JDBC.

JDBC Update query error

I can't execute the update query on JDBC with where clause. I want to execute the query by concatenating some variables.
protected void updateEmail(String Email, String Username) {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "");
String query = "update access set email=" + Email + " where username=" + Username;
Statement st = conn.createStatement();
st.executeUpdate(query);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
It says:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bhusal1' in 'where clause'
String should be between two quotes 'name' instead of your way you have to use PreparedStatement instead to avoid syntax error or SQL Injection :
String query = "update access set email=? where username=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.executeUpdate();
This is most likely a problem with concatenation of the request. The approach you use is extremely bad and can cause any problems (including security).
To avoid problems, use PrepareStatement when you need to submit sql query parameters.
Here's an example that should solve your problem:
void updateEmail(String email,String username) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "")) {
String query = "update access set email = ? where username = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, email);
statement.setString(2, username);
statement.executeUpdate();
}
}
catch (SQLException e) {
System.out.println(e);
}
}
You should put your variables email and username between quotes in the where clause to be able to do the update query

Trouble retrieving data with JDBC in Eclipse IDE

I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly

Validate username and password in phpmyAdmin

I am trying to validate a database (phpMyadmin) using Username and Password. I need to search in all the tables (25 tables in my database) for checking if the given username and password are present (Authentication) or not. Can anyone provide the query to search entire table using the given username and password?
Below is my code
public class Dbclass {
/**
* #param args
*/
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
ResultSetMetaData metaData = null;
String DB_URL="com.mysql.jdbc.Driver";
String USER="java";
String PASS="redhat";
String username;
String password;
ResultSet rs;
public ResultSet dbConnection(String query)
{
//STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
//sql = "SELECT username,password FROM Employees";
rs = stmt.executeQuery(query);
while(rs.next()){
//Retrieve by column name
username = rs.getString("user_name");
password = rs.getString("password");
//Display values
System.out.print("User_name: " + username);
System.out.print(",Password: " + password);
}
Authentication obj=new Authentication();
obj.userLogin(username,password);
//STEP 6: Clean-up environment
//rs.close();
//return rs;
stmt.close();
conn.close();
} catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException es) {
//TODO Auto-generated catch block
es.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(conn!=null){
conn.close();
}
if (rs != null) {
rs.close();
}
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return rs;
}
}
I guess you're looking for a where clause. Something like below.
SELECT username,password FROM Employees where username='usernm' and password='pwd'
If required, you can add UNION to merge more such queries, but not recommended due to performance issues.

Categories