I am building a simple security system using java (eclipse) and I am using the MYSQL statement to pull data from the database
ResultSet rs = statement.executeQuery("select name, username, password from securitysystem.employee where username = '" + username + "' and password = '" + password + "'");
but what if i wanted to create a variable user= name, how would I do that? name is referring to the name retrieved using the statement above.
Firstly, you should never put your parameter right into a query string.
Instead, do this:
PreparedStatement ps = connection.prepareStatement("select name, username, password "+
"from securitysystem.employee where username = ? and password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
To get the results, do this:
if (rs.next()) { //move to 1st result row
String name = rs.getString(1); //first result column
String user = rs.getString(2); //second result column
// ..etc
}
How about:
while(rs.next()) {
String user = rs.getString("name");
}
Related
I have created a SQL login system in java but want and what to only allow people with account type 1 to access the program. The query I have written keeps coming up as errors. THE SECURITY OF THE PROGRAM IS NOT A CONCERN AS ITS JUST FOR COURSEWORK
public void login(){
try{
int a = 0;
int b =1;
String query ="select * from Users where Login = '"+
main_menu.login_text.getText()+"' and Password='"
+main_menu.passwordtext.getText().toString()+"' and Account Type='" +1+
"'" ;
rs =st.executeQuery(query);
System.out.println("Records from Database");
if(rs.next()){
f=2;
query ="select * from Users where Login = '"+
main_menu.login_text.getText()+"' and Password='"
+main_menu.passwordtext.getText().toString()+"' and Account Type='" +0+
"'" ;
rs =st.executeQuery(query);
System.out.println("Records from Database");
}
else if (rs.next()){
f=1;
}
else{
JOptionPane.showMessageDialog(null, "Incorrect Username
and Password...");
con.close();}
} catch(Exception ex){
System.out.println("Error"+ex);
}
As #luk2302 have suggested, you should change your code. With that code, you allow to be easily breach your security.
Here is an example of how to make it better:
PreparedStatement pst = null;
String sql = "SELECT * FROM login where username=? and password=?";
pst = con.prepareStatement(sql);
pst.setString(1,user);
pst.setString(2,pass);
ResultSet rs = pst.executeQuery();
Now you can just get the data you just recovered to get the information about the user. If no resul set is given, the login would have failed.
Im trying to get information in sql from database, there are two entries in each column but and with the following code, i am able to get the first entry information, if i wanted to get the second entry's records and display it also in project how would i get it?
String username1= rs.getString ("USERNAME");
String password1= rs.getString ("PASSWORD");
String aname1= rs.getString ("a_name");
String aname2= rs.getString ("a_name");
System.out.print("Enter Your Username: ");
String usernamea=(br.readLine());
System.out.print("Enter Your Password: ");
String passworda=(br.readLine());
if ((usernamea.equals(username1) && (passworda.equals(password1))))
{
System.out.println("Login Success! Welcome "+aname1+"!");
System.out.println("You are granted with Admin Acess!");
rs.close();
}
else if ((usernamea.equals(username2) && (passworda.equals(password2))))
{
System.out.println("Login Success! Welcome Guest User!");
rs.close();
}
I'm not quite sure what you are asking, nor am I sure how the code you posted actually relates to what you are asking.
When you say "you want the 2nd entry", I am assuming you mean the 2nd record in the SQL table.
try(Connection conn = DriverManager.getConnection(url, username, password)){
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
rs.next();
//All data stored in the ResultSet obj, to which you may loop through & select rows of interest. Particularly useful methods are .getMetaData(), .getRow(), etc.
}
Hopefully this is what you are asking for.
If you already have a ResultSet rs, you can call rs.next(). For Example some Code:
if (rs.next())
{
s.name = rs.getString(1);
s.creator = rs.getString(2);
s.dbname = rs.getString(3);
s.tsname = rs.getString(4);
s.cardf = rs.getFloat(5);
s.npages = rs.getInt(6);
s.statstime = rs.getString(7);
s.avgrowlen = rs.getInt(8);
}
Considering your code:
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
String username1 = rs.getString ("USERNAME");
String password1 = rs.getString ("PASSWORD");
String aname1 = rs.getString ("a_name");
rs.next();
String username2 = rs.getString ("USERNAME");
String password2 = rs.getString ("PASSWORD");
String aname2 = rs.getString ("a_name");
Now you can check both the first entry and the second.
Nevertheless, the better practice is to create a user object, save username, password and aname in it.
Then, using some loop, you can go through the entire result set and get all the information from it.
ResultSet rs = stat.executeQuery("SELECT * FROM [TABLENAME]");
List<User> userList = new ArrayList<User>();
while(rs.next()) {
User user = new User();
user.setUsername(rs.getString ("USERNAME"));
user.setPassword(rs.getString ("PASSWORD"));
user.setAname(rs.getString ("a_name"));
userList.add(user);
}
I have a question. In my method
public void selectUser(String name, String surname)
I try to log user. How I can prepare an sql statment like this one:
String sql = "select * from user where surname= (here my surname from method parameter) and name= (name from method parameter) ";
Inialize your PreparedStatement object
PreparedStatement pst = null;
pst = c.prepareStatement("select * from user where surname= ? and name= ? ");
pst.setString(1, getterMethodHere);
pst.setString(2, getterMethodHere);
1,2 represents the surname= ? and name= ? symbol respectively
Learn More . .
San Krish thanks. Now how to use rs.next because i don;t understand prepareStatemnt.
Here's the code
enter code here
//stat = con.createStatement();
//String sql = "select * from user where surname= "+surname+" and name="+name;
PreparedStatement pst = null;
pst = con.prepareStatement("select * from user where surname= ? and name= ? ");
pst.setString(1, name);
pst.setString(2, surname);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
//get from column name
String id = rs.getString("id");
String login = rs.getString("login");
String password = rs.getString("password");
//print
System.out.print(" id: " + id);
System.out.print(", login: " + login);
System.out.println(", pass: " + password);
}
and how to return id ?
Hey guys I have a weird problem , if I enter my correct credentials from my database I GET AN ERROR, if I enter the wrong credentials everything is okay.
Exception in thread "main" java.sql.SQLException: Column 'username' not found.
This error occurs when I enter the correct credentials
Also I have another problem, my passwords are encrypted with MD5 and I have no idea how to write that into my SELECT , tried this but without any success.
resultSet = statement.executeQuery("SELECT password FROM cards.username WHERE username = '" + username + "' && password = 'MD5(" + password + ")'");
So this is my class
public void readDataBase() throws Exception {
//Scanners
Scanner in = new Scanner(System.in);
System.out.print("Username: ");
String username = in.nextLine();
System.out.print("Password: ");
String password = in.nextLine();
System.out.println(" ");
//---------------------
String databaseUsername = "";
String databasePassword = "";
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/cards?"
+ "user=root&password=password");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("SELECT password FROM cards.username WHERE username = '" + username + "' && password = '" + password + "'");
//writeResultSet(resultSet);
while (resultSet.next()) {
databaseUsername = resultSet.getString("username");
databasePassword = resultSet.getString("password");
}
if (username.equals(databaseUsername) && password.equals(databasePassword))
System.out.println("Success !! ");
else
System.out.println(" Failure ");
//---
//--------------------------------------------------------------------------------------------------
// resultSet gets the result of the SQL query
// resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
//
// writeResultSet(resultSet);
//
// // preparedStatements can use variables and are more efficient
// preparedStatement = connect
// .prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// parameters start with 1
// preparedStatement.setString(1, "Test");
// preparedStatement.setString(2, "TestEmail");
// preparedStatement.setString(3, "TestWebpage");
// preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
// preparedStatement.setString(5, "TestSummary");
// preparedStatement.setString(6, "TestComment");
// preparedStatement.executeUpdate();
// preparedStatement = connect
// .prepareStatement("SELECT myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// resultSet = preparedStatement.executeQuery();
// writeResultSet(resultSet);
//
// // remove again the insert comment
// preparedStatement = connect
// .prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
// preparedStatement.setString(1, "Test");
// preparedStatement.executeUpdate();
//
// resultSet = statement
// .executeQuery("select * from FEEDBACK.COMMENTS");
// writeMetaData(resultSet);
//
//---------------------------------------------------------------------------------------------------------
} catch (Exception e) {
throw e;
} finally {
close();
}
}
And this is another class where I call this method
package mysqltryouts;
import java.util.Scanner;
import mysqltryouts.MySQLtryouts;
public class main {
public static void main(String[] args) throws Exception {
MySQLtryouts dao = new MySQLtryouts();
dao.readDataBase();
}
}
This is my simple DB with only 1 table :
I am kinda new with this mySQL and Java stuff, any help would be really appreciated
*EDIT #1
Fixed the main problem, but I still don't know how to make the MD5 thing, I mean when I enter my password in java, it gets itself crypted, I've used this method in VB.NET and tried an equivalent but with no success. :
Dim SqlQuery As String = "SELECT COUNT(*) From users1 WHERE username = #Username AND password = MD5(#Password); "
My java attempt:
resultSet = statement.executeQuery("SELECT * FROM cards.username WHERE username = '" + username + "' AND password = ('MD5(" + password + ")'");
my password field is varchar(10) and I just add MD5 when I manually add the data from phpmyadmin or from my app
While retrieving from the table too, apply MD5 on your password input value to compare with database field value.
SQL statement:
select count(*) > 0 as match_found
from table_name
where username = ?
and password = md5( ? )
In JAVA:
Use PreparedStatement for value binding with the statement.
PreparedStatement pst = con.prepareStatement( sqlQuery );
pst.setString( 1, userName );
pst.setString( 2, password );
ResultSet rs = pst.executeQuery();
boolean loginSuccess = false;
if( rs.next() ) {
loginSuccess = rs.getBoolean( "match_found" );
}
I am working on a project to create a login page. To do this I am using a database to store the user information. As of right now there are four columns in my database: username, password, email, and admin.
Right now I am having a problem accessing that database using a prepared statement/Result set format. Right now I get to the third return, print out the imputed username and password then generate an error. Am I formatting my prepared statement incorrectly?
Okay, based of previous answers I have corrected most of my code(thank you) and now I have this error when I am trying to print out of the result set:
java.sql.SQLException: Column Index out of range, 2 > 1.
any ideas?
My code:
Properties props = new Properties();
props.setProperty("user", "root");
props.setProperty("password", "root");
props.setProperty("databaseName", "dbname");
String ret = ERROR;
Connection myCon = null;
try{
System.out.println("got here 1!");
Class.forName ("com.mysql.jdbc.Driver").newInstance();
System.out.println("got here 2!");
myCon = DriverManager.getConnection("jdbc:mysql://ipaddresshere:3306/dbname",props);
System.out.println("got here 3!");
System.out.println(username);
System.out.println(password);
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
//PreparedStatement prep = myCon.prepareStatement(dbQuery);"
PreparedStatement ps = myCon.prepareStatement(dbQuery);
ps.setString(1, username);
ps.setString(2, password);
ResultSet result = ps.executeQuery();
System.out.println("got here 4!");
while (result.next()) {
System.out.println("got here 5!");
ret = SUCCESS;
System.out.println("username: "+result.getString(1)+" password: "+result.getString(2)+" email: "+result.getString(3));
if(result.getString(4).toLowerCase()=="YES"){
ret = "admin";
}
}
}catch(Exception e){
System.out.println("arg there be an error me matey!");
ret = ERROR;
}finally{
if(myCon!=null){
try{
myCon.close();
}catch (Exception e){
}
}
}
return ret;
There are multiple problems with your code:
First, you're missing quotes around username and password.
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = '"+username+"' AND password = '"+password+"'";
Second, the PreparedStatement#setString() methods have no effect unless you define your query with place holders ? like
String dbQuery = "SELECT count(*) FROM loginTestTable " +
"where username = ? AND password = ?";
Third, you must never compare strings with equality == operator. Use String.equals() as
// also note you need toUpperCase() here
"YES".equals(result.getString(4).toUpperCase());
Change the line:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = "+username+" AND password = "+password+"";
By:
String dbQuery = "SELECT count(*) FROM loginTestTable where username = ? AND password = ?";