I want to retrieve a users name from the username and password that they have entered into textfields. i want to pass these values as parameter to method which will then identify the users name for printout. please help. something like this...
public void getUser(String username, String password)throws SQLException{
String qry = "SELECT UserName From USER....";
Connection con = null;
PreparedStatement stmt = null;
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.executeUpdate();
If not is an update or an insert, don't use executeUpdate()
You must use executeQuery().
Try this:
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT UserName From USER where username=? and password=?";
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("UserName"));
}
...
Regards
Assuming that you want to get the user's full name from db and your table structure is something like this:
fullname | username | password
you could do the following:
Connection c = null;
PreparedStatement s = null;
try {
c = DriverManager.getConnection("URL");
s = c.prepareStatement("SELECT fullname FROM user WHERE username=? and password=?");
s.setString(1, username);
s.setString(2, password);
ResultSet rs = s.executeQuery();
if(rs.next())
return rs.getString("fullname");
return null; // no user found!
} catch(SQLException e) {
System.err.println(e.getMessage());
} finally {
// close s and c
}
Note: This assumes that the password that is passed to the method is in the same "form" as it is stored in db (i.e. either plain text or hashed (+salted))
try this its very simple example
private boolean validate_login(String id,String password) {
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
Related
I'm trying to make a register page into my servlet project.
If the username is already taken, I want to show an error message.
Heres my code :
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/covid","root","fbfbfb333*");
String query = "SELECT * FROM users WHERE username = ?";
pstmt = (PreparedStatement) con.prepareStatement(query);
pstmt.setString(1, uname);
rs = pstmt.executeQuery();
if(rs.next()) {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
} else {
System.out.println("Username " + uname + " already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
But when I add a new users , it says " username already taken " whether it exist or not.
What should I do?
Switch the condition, if there is a result set data means that the username is taken, else insert new username
if(rs.next()) {
System.out.println("Username " + uname + " already exists.");
} else {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
}
I want to insert logical operations (=,<,>=,<,>=) in my sql
try {
String sql = "SELECT id,name,date_N FROM LECTEUR WHERE date_N ?,?";
Connection con = DBinfo.getConnection();
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, operationCB.getValue());
ps.setString(2, date1.toString());
ResultSet resultSet = ps.executeQuery();
output:
Incorrect syntax near '#P0'.
You can only insert values as parameters of the PreparedStatement.
If you want the operation to be dynamic, use a StringBuilder to build the query String:
StringBuilder sql = new StringBuilder();
sql.append("SELECT id,name,date_N FROM LECTEUR ");
sql.append("WHERE date_N ");
sql.append(operationCB.getValue());
sql.append(" ?");
Connection con = DBinfo.getConnection();
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql.toString());
ps.setString(1, date1.toString());
ResultSet resultSet = ps.executeQuery();
You cannot bind a logical operator to a prepared statement using a ? placeholder. One workaround would be to maintain separate queries for the various logical operations:
Map<String, String> queryMap = new HashMap<>();
queryMap.put("=", "SELECT id, name, date_N FROM LECTEUR WHERE date_N = ?");
queryMap.put(">", "SELECT id, name, date_N FROM LECTEUR WHERE date_N > ?");
// etc.
try {
String sql = queryMap.get(operationCB.getValue()); // fetch the appropriate statement
Connection con = DBinfo.getConnection();
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setDate(1, date1);
ResultSet resultSet = ps.executeQuery();
} catch (SQLException e) {
// handle exception
}
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd1 = request.getParameter("pass");
String pwd2 = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/logindb";
Connection con = DriverManager.getConnection(url, "root", "root");
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ResultSet rs = ps.executeQuery();
if(rs.next())
{
sql = "update register set pass=? where uname=? ";
ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ps.executeUpdate();
out.println("password changed");
}
}
catch(Exception e)
{
out.println(e);
}
This Is my code and it will show me an error like this
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).**
Here:
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
You are trying to set parameters that aren't there. Looks like a copy-and-paste error. Those last 2 lines shouldn't be there.
I have this query:
Connection conn = null;
stmt = conn.createStatement();
stmt.execute("SELECT * FROM school.users");
and I got results from that query. If I try to implement this following code in java to set a default database:
stmt.execute("database school");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
I have this error:
Exception-> [Teradata Database] [TeraJDBC 14.10.00.17] [Error 3807] [SQLState 42S02] Object 'users' does not exist
Can You see what is Wrong?
Add DATABASE param in the url and try.
eg. url="jdbc:teradata://exampleDns/DATABASE=school"
I hope this is what you are looking for
Try this:
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
}
catch(SQLException se){
se.printStackTrace();
finally{
stmt.close();
conn.close();
}
What if you use the executeUpdate "method" of the Statement?
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
stmt.executeUpdate("database school");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
I get an error in this method:
public String databaseServer(String email)throws IllegalArgumentException {
Connection dbCon = null;
Statement stmt = null;
String password = null;
System.out.print(email);
String query = "SELECT password FROM user WHERE email = ?";
try {
dbCon = initializeDBConnection();
PreparedStatement preparedStatement = dbCon.prepareStatement(query);
preparedStatement.setString(1, email);
ResultSet rs = preparedStatement.executeQuery(query);
while (rs.next()) {
password = rs.getString("password");
}
} catch (SQLException ex) {
Logger.getLogger(Collection.class.getName())
.log(Level.SEVERE, null, ex);
}
//close connection ,stmt and resultset here
return password;
}
The error is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
I've checked the connection and the incoming string and they both work fine.
Anybody knows what I'm doing wrong?
Instead of
ResultSet rs = preparedStatement.executeQuery(query);
do
ResultSet rs = preparedStatement.executeQuery();