I have a login arraylist where i have stored users loginid using following mysql query
Code:
query = "select LoginID from issuedeposit id where id.DueDate < CURDATE()";
result = statement.executeQuery(query);
while(result.next())
{
String loginid = result.getString(1);
loginarray.add(loginid);
}
now I want to use the loginid values stored in the above arraylist to fetch users emailid form other table. I am using following query
Code:
for(int i=0;i<=loginarray.size();i++)
{
res = statement1.executeQuery("select EmailID form studentaccount sa where sa.LoginID = '"+ loginarray.get(i) +"' ");
String email = res.getString(1);
emailarray.add(email);
}
but am getting error in the above query. So have i correctly used the for loop or it should be used inside the query...?
I am using JDBC and MySql
res = statement1.executeQuery("select EmailID form studentaccount sa
where sa.LoginID = '"+ loginarray.get(i) +"' ");
Should be
res = statement1.executeQuery("select EmailID FROM studentaccount sa
where sa.LoginID = '"+ loginarray.get(i) +"' ");
Related
Why mysql query string query ="select * from " + table + "";` is not working the table name is coming from another jsp page.
And why session. setAttribute ("", "table");` is not working to import string from jsp to jsp?
I have two jsp file in my code one is for selection of table for username and password to get login the file name is statement.jsp and other file statement is for showing data in a table that is selected in statement3.jsp. I want to use table string in another jsp page to show that table.
error
String query ="select * from " + table + ""; //for selection of table
session.setAttribute("", "table"); //To pass String table from statement.jsp to statement3.jsp to show table.
statement3.jsp
<%
ResultSet rs = null;
session.setAttribute("", "table");
String query ="select * from " + table + "";
rs=st.executeQuery(query);
%>
statement.jsp
<%
ResultSet rs = null;
String name=request.getParameter("username");
String abc=request.getParameter("password");
String gender = request.getParameter("gender");
if (gender != null) {
String table = gender.equals("teacher") ? "teacher2" : "student";
out.println(table);
String query ="select * from " + table + " where username='"+name+"' AND password='"+abc+"'";
rs=st.executeQuery(query);
out.println(rs);
if(rs.next())
{
response.sendRedirect("statement3.jsp");
}
else
{
response.sendRedirect("index.jsp");
}}
%>
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:93)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:435)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:298)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:277)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:265)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:302)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
If you want to put the value of the variable table in the session you can do this:
String table = "whateverTableNameYouWant";
session.setAttribute("mySessionVariableName", table);
If you want to read that value in another jsp, you can do this:
String table = (String)session.getAttribute("mySessionVariableName");
I am new to DATABASE and MYSQL so don't have much experience or knowledge with handling queries
I have two tables students and login in MYSQL database, they both have 1:1 relation, Primary key of student is a foreign key in login.
So login table has both Student_ID(FK) and Password
I want to run a query in a JAVA program that will check the id and password entered by the user in login table and then return the matching student object data from student table
So far this is what I am doing for login the user put in username and password
public Student validate_Student(String s, String t)
{
int w = Integer.parseInt(s);
int q = 0;
String iD = "";
Student obj = new Student();
String query = "SELECT * FROM login WHERE Student_ID = " + w + " and Password= " + t;
try
{
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
iD = rs.getString("Student_ID"); //matching record
}
int i = Integer.parseInt(iD); // check the previously searched matching record in student table
String query1 = "SELECT * FROM student WHERE ID = " + i;
ResultSet rs1 = stmt.executeQuery(query);
while (rs1.next()) {
obj.setID(rs1.getString("ID"));
obj.setName(rs1.getString("NAME"));
obj.setAddress(rs1.getString("ADDRESS"));
obj.setPhone(rs1.getString("PHONE_NO"));
obj.setEmail(rs1.getString("EMAIL"));
obj.setDOB(rs1.getString("DOB"));
obj.setDegree(rs1.getString("DEGREE"));
}
}
catch(SQLException e)
{
System.out.println("Problem in Query");
e.printStackTrace();
}
return obj;
}
I am not quite sure how to use UNIONS in the query
Below query will return student details whose login credentials match.
SELECT s.* FROM student s JOIN login l on s.id = l.Student_ID WHERE l.Student_ID = " + w + " and l.Password= '" + t + "'";
Join student table to login table using one to one relation s.id = l.Student_ID where s is the alias for student table and l for login table.
to return only student details use s.* in select statement.
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");
}
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 = ?";
I have the working code here to pull all info that I need from my users and user info table located in an oracle database :
try
{
conn = DB_Admin.getConnection();
pstmnt = conn.prepareStatement("SELECT u.username, u.password, ui.user_id, " +
"ui.f_name, ui.l_name, ui.email, ui.dob FROM users u " +
"JOIN user_info ui ON ui.user_id = u.user_id " +
"WHERE u.username = ? AND u.password = ?");
pstmnt.setString(1, username);
pstmnt.setString(2, password);
rs = pstmnt.executeQuery();
boolean exists = rs.next();
...
And I have a servlet which is I am trying to make display the users first name after he/she logs in:
String username = request.getParameter("username").toString();
String password = request.getParameter("password").toString();
User user1 = new User(username, password);
User user2 = new User(username,password, user1.getF_name(), user1.getL_name(), user1.getEmail(), user1.getDob());
//HttpSession session = request.getSession();
//session.setAttribute("f_name", user1.getF_name());
boolean valid = ud.login(username, password);
try{
if(!valid)
{
// request.setAttribute("var", companies);
response.sendRedirect("login.html");
logger.warn("Login Servlet : " + username + " has failed at logging in");
}
else
{
//response.sendRedirect("index.jsp");
request.setAttribute("f_name",user2.getF_name());
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
logger.info("Login Servlet : " + username + " has logged in");
}
}
catch (Exception ex) { out.println(ex.getMessage()); }
In my User class I have getters and setters for all fields: "f_name, email, etc."
I know this code is written incorrectly, and I keep getting a "null" value on my welcome page.
First you should be able to get data you need from the executed query this way
String username = null;
while(rs.next){
username = rs.getString(1);
}
rs.getString method can be called either by index of columns in the order you have made in the executing query OR you can simple place the number by the name of the column of the original database
for example:
username = rs.getString("username");
Here you have the username returned in the executed query and you can easily print it in the jsp