Prepared statement error when trying to receive password from DB - java

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();

Related

Java Prepared Statement syntax to connect hive server for describing table

trying to establish connection to hive and describe a table.
enter code here
String queryTable= "dummydb.dummy_table";
String driverName = "org.apache.hive.jdbc.HiveDriver";
try {
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//connect hive server (no issue in that)
String hiveUrl = PropertyLoader.getInstance("staging").getDruidHive();
Connection con = DriverManager.getConnection(hiveUrl, "hadoop", "");
##Working code is below:
String sql = "describe formatted dummydb.dummy_table" ;
PreparedStatement pstmt = con.prepareStatement(sql);
ResultSet rs1 = pstmt.executeQuery();
##But I try to use this which is not working:
String queryTable="dummydb.dummy_table"
String sql1 = "describe formatted ?" ;
PreparedStatement pstmt = con.prepareStatement(sql1);
pstmt.setString(1, queryTable);
ResultSet rs1 = pstmt.executeQuery();
Error
org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 1:19 cannot recognize input near 'formatted' ''dummydb.dummy_table'' '' in describe statement

Unable to connect to LAN server; no exception is shown

I have tried to use another proyect and the connection is succesfull but from this proyect I am only able to connect to localhost mysql. I want it to work only on lan.
I am getting "Access denied for user 'root'#'192.168.1.70' (using password: YES)"
Code sample from not working proyect:
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{ con = (Connection) DriverManager.getConnection("jdbc:mysql://"+home.credentials[0],home.credentials[1],home.credentials[2]);
st = (Statement) con.createStatement();
String s = "SELECT * FROM meta";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
while(rs.next()){
int meta = rs.getInt("meta");
goal.setText(Integer.toString(meta));
}
}catch(Exception e){}
finally{
try{ st.close();
rs.close();
con.close();
}
catch(Exception e){ JOptionPane.showMessageDialog(null, "InformaciĆ³n no encontrada");
}
}
Code sample from another proyect which connects succesfully
try
{
// create our mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://192.168.1.66:3306/jjeventoscore";
Class.forName(myDriver);
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM client";
// create the java statement
Statement st = (Statement) conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next()){
String name = rs.getString("name");
String last = rs.getString("last");
String h_phone = rs.getString("h_phone");
String m_phone = rs.getString("m_phone");
String of_phone = rs.getString("of_phone");
String ex_phone = rs.getString("ex_phone");
String email = rs.getString("email");
String medium = rs.getString("medium");
System.out.println(name+" "+last);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
You need to give privileges to the user on that Database and that Table.
With privileges, on your MySQL instance:
USE jjeventoscore;
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70';
Or maybe try
GRANT ALL ON jjeventoscore.* TO 'root'#'192.168.1.70' IDENTIFIED BY '';
Since it says "Using password: YES"
Also, check the password on MySQL. It should match the parameter in this function
Connection conn = (Connection) DriverManager.getConnection(myUrl, "root", "");

I have created a search bar in java. But it has some errors

try {
con = DriverManager.getConnection(url, username, password);
String qry = "SELECT * FOME users WHERE id=?";
pst = con.prepareStatement(qry);
pst.setString(1, txtSearch.getText());
rs = pst.executeQuery();
tblEmployee.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace(); //Show what is the catched error
}
rs = pst.executeQuery(); doesn't work and throws following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'FOME users
WHERE id='df'' at line 1
You should have believed the error. FOME should be FROM,
String qry = "SELECT * FROM users WHERE id=?";
There is a type in SQL statement. It should be
String qry = "SELECT * FROM users WHERE id=?";
Notice the typo, FOME.
Whenever you get exceptions like these, first execute the query using SQL client before doing it through Java.

preparedStatement SQL Error

Here is my code:
public int checklogin(String email, String key){
int res = -1;
try
{
String selectSQL = "SELECT id FROM table WHERE email = ? AND key = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, email);
preparedStatement.setString(2, key);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
res = rs.getInt("id");
rs.close();
preparedStatement.close();
} catch (Exception e) { e.printStackTrace(); }
return res;
}
But i get:
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 'key = 'AAA'' at line 1
Where is the problem?
KEY is a reserved word in MySQL. It needs to be escaped
String selectSQL = "SELECT id FROM table WHERE email = ? AND `key` = ?";
Avoiding the reserved keywords is always the best solution when naming column names.

Retrieving a specific value from mysql database based on parameters

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;
}
}

Categories