Field can be converted to local variable - java

I have this error: Field can be converted to local variable.
for preparedStatement
package game;
import java.sql.*;
public class db {
private Connection connection;
private PreparedStatement preparedStatement;
public db() throws SQLException,ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/riverraider";
String user = "root";
String pass = "146155";
connection = DriverManager.getConnection(url,user,pass);
}
public String select(String username, String password) throws Exception
{
preparedStatement = connection.prepareStatement("SELECT * FROM `user` WHERE `username`=? AND `password`=? ");
preparedStatement.setLong(1, Long.parseLong(username));
preparedStatement.setLong(1, Long.parseLong(password));
ResultSet result = preparedStatement.executeQuery();
while (result.next()!=false){
System.out.println("Username or password is incorrect.");
}
}
}

Most likely, the error/warning is just stemming from your declaring the variable preparedStatement as a class level variable, when it can just be a variable local to the select() method with the same effect. Try removing that declaration from the class level, and instead using this version of select():
public String select(String username, String password) throws Exception {
String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1, Long.parseLong(username));
ps.setLong(1, Long.parseLong(password));
ResultSet result = ps.executeQuery();
while (result.next() != false) {
System.out.println("Username or password is incorrect.");
}
}
I also tidied up your code a bit to make it easier to read. You don't need backticks around your column names, because they are not reserved keywords (nor should they be).
Note: I'm not sure that your username and password columns are actually numeric. More likely, I would expect at least the username to be text of some sort. But, this would result in an error other than the one you reported in your question.

Related

Checking username and passwords against MySQL is returning blank

I am doing username and password check against MySQL database but somehow my code is returning none even for the base case (email does not exist). I hash my passwords on the server side. What should I fix in this case?
package GUI_755;
import java.sql.*;
import nonGUI_755.AES;
public class test {
public static void main(String args[]) throws Exception {
System.out.println(loginResponse("jordan30#bulls.edu","JordanTheGoat3098"));
}
/* The method handles the login's request from the user */
public static String loginResponse(String email, String password) throws Exception{
String returnStatement = "";
Connection connection = null;
connection = establishConnection();
/* Similar to the code above, we check whether the email and password match to those we have in the database */
final String queryCheck = "SELECT * from usersdata WHERE email = ?";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
ps.setString(1, email);
final ResultSet resultSet = ps.executeQuery();
try {
/* First, if we cannot find the user's email, we return this statement */
if(email.equals(resultSet.getString("email"))) {
/* Second, if we can find the email but the password do not match then we return that the password is incorrect */
String hashedPasswordInput = AES.doHash(password, resultSet.getObject("password").toString().split("\t")[1]);
if(hashedPasswordInput.equals(resultSet.getObject("password").toString().split("\t")[0])) {
returnStatement = "LoginFailure The password that you entered is incorrect. Please try again!";
connection.close();
}
else {
returnStatement = "LoginSuccess You are logged in!";
}
}
else {
connection.close();
returnStatement = "LoginFailure We cannot find any account associated with that email. Please try again!";
}
}catch(Exception e) {}
return returnStatement;
}
/* This method will connect to MySQL database >> userdata */
public static Connection establishConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/userdata","root","");
return connection;
}catch(Exception e)
{return null;}
}
}
You need to check if your ResultSet resultSet is returning some rows. For that, you should use next() method of ResultSet. You can use if (resultSet.next() if you are interested in only first row (like your case here) or while (resultSet.next()) if you want to loop over the returned result rows (not your case).
So to put it together:
final String queryCheck = "SELECT * from usersdata WHERE email = ?";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
ps.setString(1, email);
final ResultSet resultSet = ps.executeQuery();
if (resultSet.next()) {
/* First, if we cannot find the user's email, we return this statement */
if(email.equals(resultSet.getString("email"))) {
/* Second, if we can find the email but the password do not match then we return that the password is incorrect */
String hashedPasswordInput = AES.doHash(password, resultSet.getObject("password").toString().split("\t")[1]);
if(hashedPasswordInput.equals(resultSet.getObject("password").toString().split("\t")[0])) {
// dont do it here
// returnStatement = "LoginFailure The password that you entered is incorrect. Please try again!";
// connection.close();
}
else {
returnStatement = "LoginSuccess You are logged in!";
}
}
else {
// don't do it here
// connection.close();
// returnStatement = "LoginFailure We cannot find any account associated with that email. Please try again!";
}
}

My Java SQL Update statement is not updating my database, and I don't know if it's a problem with the statement or the connection

I am connecting my Java Program to a database stored in the program folder, and I am having users answer quiz questions and I want the results to be stored in the database. The Update statement is not working, and I don't know if it's a problem with the actual statement or the database connection.
I've tried creating a new database with the same tables and reconnecting to that database, but nothing seems to be working.
//database connection class
public class databaseConnection {
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager
.getConnection("jdbc:sqlite:D:\\Users\\mariammahmoud\\eclipse-workspace\\ia_2019_final\\testjava.db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
public class student {
public static final String DB_NAME = "testjava.db";
public static final String TABLE_STUDENTS = "students";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GRADE = "grade";
public static final String COLUMN_RESULTS = "results";
public static final String COLUMN_EVENTS = "events";
public static final String COLUMN_USERNAME = "username";
public void main() {
try {
String user_name = login_student.sendQuiz();
Connection conn = databaseConnection.dbConnector();
ArrayList<String> results = new ArrayList<String>(15);
instructions();
questions(results);
results.trimToSize();
System.out.println("Here are the events that you should consider competing in:");
System.out.println(results);
String separator = ",";
int total = results.size() * separator.length();
for (String finalResults : results) {
total += finalResults.length();
}
StringBuilder sb = new StringBuilder(total);
for (String finalResults : results) {
sb.append(separator).append(finalResults);
}
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = " +user_name;
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Something went wrong:" + e.getMessage());
e.printStackTrace();
}
}
I expected the update statement to update the testjava.db database, but everything is staying the same. What should I do? Thank you in advance!
Your problem is that while you wisely used a prepared statement in your code for the update, you never actually used it for the username column in the WHERE clause. Hence, the query you are executing currently won't be interpreted as comparing some input against username. Rather, the username value will be interpreted as a column. Try this version:
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = ?";
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.setString(2, user_name);
myStmt.executeUpdate();
Note that you could have just tried the following:
String sql = "UPDATE students SET events = ? WHERE username = '" + user_name + "'";
But, please bind a value to a ? placeholder instead, as I have suggested above. One benefit of using statements is that it frees you from having to worry about how to escape your data in the query.

how to insert a variable in SQL which is already defined in the code

public class DB
{
public static void main(.....)
{ String str="hello";
....
st.executeUpdate("insert into r2( col1) values(.....)"); // here r2 is the table in which i want to insert the "str" defined above.
}}
i want to insert this 'str' in the table r2 using the insert command.
WHAT DO I WRITE HERE? TO INSERT VALUE OF "str" PREVIOUSLY DEFINED , how to pass the parameter 'str' from outside such that it gets inserted into the table??
You will write it like this .. assuming column name in table r2 is col1
public class DB
{
public static void main(.....)
{ String str="hello";
.... // Obtain DB Connection here
PreparedStatement ps = connection.prepareStatement("insert into r2( col1) values(?)";
ps.setString(1,str);
ps.execute();
}
}
The safest way is to use a Prepared Statement.
Here is Oracle's very comprehensive tutorial on using Prepared Statements.
In your case (assuming the column you want to insert the value into is named "world") it would be done something like this:
String str="hello";
Connection connection = [...] // Set up connection
String queryString = "insert into r2 ('world') values(?)";
Statement statement = connection.prepareStatement(queryString);
statement.setString(1, str);
statement.executeUpdate();
// Add exception handling, clean-up
Try it and see if it helps.
public class Example {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
PreparedStatement ps = conn.prepareStatement("insert into table_name( col1,col2,col3) values(?,?,?)";
ps.setString(1,str);
ps.setString(2,str);
ps.setString(3,str);
ps.execute();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Display rows in database using java

I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}

NullPointerException when using executeQuery

I have a null pointer exception in
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
my code is like this :
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}
Most likely aStatement is null.
Sounds like you think aStatement should not be null, but it is.
This is bad JDBC code, for many reasons:
No cleanup of resources.
Doesn't use PreparedStatement
Keeps creating the query string over and over again instead of using a static variable
Doesn't follow Java coding standards ("Query" should be "query")
Here's another way to write it. Start with an interface:
package persistence;
import java.sql.SQLException;
public interface CredentialDao
{
boolean isValidUser(String username, String password) throws SQLException;
}
Write an implementation:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CredentialDaoImpl implements CredentialDao
{
private static final String CREDENTIAL_QUERY = "SELECT COUNT() FROM USER WHERE USERNAME = ? AND PASSWORD = ?";
private Connection connection;
public CredentialDaoImpl(Connection connection)
{
this.connection = connection;
}
public boolean isValidUser(String username, String password) throws SQLException
{
boolean isValidUser = false;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = this.connection.prepareStatement(CREDENTIAL_QUERY);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next())
{
int count = rs.getInt(1);
isValidUser = (count > 0);
}
}
finally
{
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return isValidUser;
}
}
The aStatement variable is apparently null, please validate that it is correctly set. You should consider read the Java Naming Conventions and make sure you use the lower camel case for variables and java bean conventions.
For code snippets in stackoverflow if they are not self-explanatory, you should obey the rules of the SSCCE, this will help you to get more and better answers. Also you should provide a stack trace with the occured exception.
Use prepared statements.
Connection con = ...; // obtain connection here
PreparedStatement pstmt = con.prepareStatement("select * from TBL_Users where userName = ?'");
pstmt.setInt(1, userName);
ResultSet rs = pstmt .executeQuery();
...
// do clean up here
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true; // Huh? What?
}
What is info refering to and why is there a return imediatly after the assignments?

Categories