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);
}
Related
All I am trying to do is pull the integer value from the cell. When I run the command in my sql workbench I get the proper value screenshot of db output however when I execute the code in programming environment I get "An exception occurred processing [/registration.jsp] at line [24]" which is this line idnum = rs.getInt("MAX(idnum)")+1; The program has an initial html page where the use enters the desired password, first name and last name. it then sends the info to the jsp which is supposed to take that information increment the user id by 1 from whatever the highest value is currently then create a new table entry with said information.
int idnum = 0;
String pwd = request.getParameter("pwd");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment2", "root",
"has the actual password in the code");
Statement stmt = conn.createStatement();
String query = "SELECT MAX(idnum) FROM users";
ResultSet rs = stmt.executeQuery(query);
idnum = rs.getInt("MAX(idnum)")+1;
Replace
idnum = rs.getInt("MAX(idnum)")+1;
with
if (rs.next())
idnum = rs.getInt(1)+1;
Note that without calling the next() method, the result set pointer/cursor will not move to the 1st row (from default position).
This should work:
String query = "SELECT MAX(idnum) as maxNum FROM users";
ResultSet rs = stmt.executeQuery(query);
if(rs.next(){
idnum = rs.getInt("maxNum")+1;
}
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String query;
boolean login = false;
String username = jTextField1.getText();
String password = jTextField2.getText();
try{
query = "SELECT (cUsername AND cPassword) FROM Customer WHERE cUsername = '"+username+"' AND cPassword = '"+password+"'";
pst = conn.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery();
String userCheck = rs.getString(1);
String passCheck = rs.getString(2);
if((userCheck.equals(username)) && (passCheck.equals(password)))
{
login = true;
System.out.println("It actually works?!");
}
else
{
login = false;
System.out.println("Psyche, that's the wrong number!");
}
}
catch(Exception e){
System.out.println(e);
}
System.exit(0);
}
I'm currently having difficulty implementing a login system in my code. I'm trying to retrieve the text from username and password jTextFields and then query them to the database but it's not working. At the moment I'm getting
java.lang.ArrayIndexOutOfBoundsException: 0
and I unfortunately have no idea why. Any help would be GREATLY appreciated.
Your query and the logic behind got a lot of work to do:
First of all, if you want a parametrised query, you must use '?' instead of the value. Then the pst.setString will work.
Secondly, you must affect the pst.executeQuery(); to a ResultSet
query = "SELECT cUsername, cPassword FROM Customer WHERE cUsername = ? AND cPassword = ?";
pst = conn.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
String userCheck = rs.getString(1);
String passCheck = rs.getString(2);
}
public int addUsers(int USER_ID,String FIRST_NAME,String LAST_NAME,String PASSWORD,String USERNAME,String USER_PERMISSION) throws SQLException {
Connection conn = null;
conn = getConnectivity(conn) ;
getConnectivity(conn);
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equals(USERNAME)){
System.out.println("Username already exists");
conn.close();
}
else{
System.out.println("FOUND ELSE");
String sql = "INSERT INTO USER_DETAILS VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, USER_ID);
ps.setString(2, FIRST_NAME);
ps.setString(3,LAST_NAME);
ps.setString(4,PASSWORD);
ps.setString(5,USERNAME);
ps.setString(6,USER_PERMISSION);
int result = ps.executeUpdate();
System.out.println(result);
}
}
conn.close();
return USER_ID;
}
and for login I am using
public boolean login(String USERNAME, String PASSWORD) throws SQLException
{
boolean result = false;
Connection conn = null;
conn = getConnectivity(conn) ;
String sqlSelect = "SELECT * from USER_DETAILS";
PreparedStatement pres = conn.prepareStatement(sqlSelect);
ResultSet rs1 = pres.executeQuery();
if(rs1.next()){
String Username = rs1.getString(5);
String Password = rs1.getString(4);
String UserPermission = rs1.getString(6);
System.out.println("username found "+Username);
System.out.println("username input " + USERNAME);
System.out.println("password input " + PASSWORD);
if (Username.equalsIgnoreCase(USERNAME) && Password.equalsIgnoreCase(PASSWORD) && UserPermission.equalsIgnoreCase("blocked")){
System.out.println("User Logged in");
conn.close();
}
System.out.println("gets out of the code");
}
conn.close();
return result;
}
first of all it is allowing to enter more than one entry, so duplicates occurring regardless of my if statement, and when i add fresh new data and try to see I can log in, it still compares with previously added data and does not work. Can someone see what am i doing wrong here. please thanks
below is the system print out i get ,
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macbook (these i have already in my database)
password input hello (these i have already in my database)
gets out of the code
Connection Valid
Connection Valid
username found kamran (don't know why he is still picking up this column)
username input macho (these i have already in my database)
password input hello (these i have already in my database)
FOUND ELSE (dont know why it adds data when they already exist in database)
1
Your code doesn't make sense: you are querying for all users and only checking the first returned user if it matches. Of course that is going to fail if the first returned user doesn't match: in addUsers you will try to add the user if the first user returned doesn't match, in login a user can only login if it is the first user.
You need to use a WHERE clause to only request the user you want to check:
// Note: this assumes a case insensitive collation
String sqlSelect = "SELECT * from USER_DETAILS WHERE username = ?";
try (PreparedStatement pres = conn.prepareStatement(sqlSelect)) {
pres.setString(1, USERNAME);
try (ResultSet rs1 = pres.executeQuery()) {
if (!rs1.next) {
// user doesn't exist yet, create...
}
}
}
You need to do something similar for login (but then with if (rs1.next()) instead).
There are more problems with your current code: you are storing plaintext passwords: you should really hash them with a strong password hash like PBKDF2. Also please follow the java naming conventions. Variables and parameters are camelcase so not USERNAME but username (or userName), not UserPermission, but userPermission. This improves the readability for people who are used to the java naming conventions.
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");
}