I am getting a syntax error with the SQL code within a prepared statement. I have read the other answers on the site and I cannot work out the issue. My code is as follows
private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
String url = "jdbc:mysql://localhost/db_webstore";
String user = "root";
String pw = "Password";
String SQL = "select * from tbl-users where Tbl-UsersUserName=? and Tbl-UsersPassword=?";
Connection conn = DriverManager.getConnection(url, user, pw);
PreparedStatement pst;
pst = conn.prepareStatement(SQL);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
The error message is as follows
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 '-users where Tbl-UsersYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-users where Tbl-Users
Can anyone offer some advice? Thanks in Advance
You are probably missing some dots in your query. Table and column name need to be separated by a dot. Furthermore the table name needs to be quoted as - is not allowed in unquoted identifiers (see here):
String SQL = "select * from `Tbl-Users`"
+ " where `Tbl-Users`.UserName=?"
+ " and `Tbl-Users`.Password=?";
UPDATE:
Added link to MySQL docu on valid identifiers
Quoted table name using `
you should include the port number(which is 3306 for MySQL) in your database connection
accordingly your code should be corrected as follows
private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
String url = "jdbc:mysql://localhost:3306/db_webstore";
String user = "root";
String pw = "Password";
String SQL = "select * from tbl-users where Tbl-UsersUserName=? and Tbl-UsersPassword=?";
Connection conn = DriverManager.getConnection(url, user, pw);
PreparedStatement pst;
pst = conn.prepareStatement(SQL);
pst.setString(1, username);
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 need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.
I have read something about typing the question mark like \'?'// but I am not sure about the exact format.
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = con.createStatement();
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
ResultSet rs = stmt.executeQuery(sql);
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!
You are executing the query using a normal java.sql.Statement, not using a java.sql.PreparedStatement. This won't work because a normal Statement does not support parameterized queries. So, remove the creation and execution of the Statement, and make sure you execute the statement using the PreparedStatement:
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement preparedStmt = con.prepareStatement(sql)) {
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
try (ResultSet rs = preparedStmt.executeQuery()) {
// process result set
}
}
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.
I am trying to list MySQL databases and their tables with Java. For now, I have two databases as "Database_Services with MySQL_Database_Service, MSSQL_Database_Service, and Directory_Services with Active_Directory, OpenLDAP tables. I get the output for Database_Services and its tables but I do not get the other ones.
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
I want to get an output like:
Database_Services:
MySQL_Database_Service.
MSSQL_Database_Service.
Directory_Services:
Active_Directory_Service.
OpenLDAP_Service.
You are using the same Statement for multiple queries. You cannot do that. From the Javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
if you have more than 2 database, then simply you can use loop for to get the results.
You can use the meta information database information_schema.
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA
I am creating an Application (Using Java & SQLite)(JFrame, using Netbeans) I have users who I want to log in. (I have all the correct packages JDBC, SQLite etc)
The issue I am having seems to be getting the username/password to check against my users.db file.. I am using Java and SQLite. I'm using JDBC also.
Some of my code as an example (This sends my users information to make the account, Works fine), my database is users.db and I want to compare username/password against USERNAME & PASSWORD
Connection dbconn = null;
Statement stmt = null;
String query = "insert into USERS(ID, FIRSTNAME, SECONDNAME, USERNAME, PASSWORD, JAVALESSON, CLESSON, PYTHONLESSON) values(?, ?, ?, ?, ?, ?, ?, ?)";
try {
Class.forName("org.sqlite.JDBC");
dbconn = DriverManager.getConnection("jdbc:sqlite:users.db");
Statement statement = dbconn.createStatement();
PreparedStatement pstmt = dbconn.prepareStatement(query);
I have a UsernameLoginBox & PasswordLoginBox, How would I check USERNAME & PASSWORD (From SQLite Database) against the string in the textbox's for log in?
TRIED CODE:
Connection conn = null;
ResultSet rs =null;
PreparedStatement pst =null;
String sql1 = "Select * from USERS where USERNAME=? and PASSWORD=?";
try{
pst = conn.prepareStatement(sql1);
pst.setString(1, UsernameLogIn.toString());
pst.setString(2, PasswordLogInField.getText());
rs=pst.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Username & Password are correct");
} else {
JOptionPane.showMessageDialog(null, "Username & Password are incorrect");
System.out.println("Logged in");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
System.out.println("Not Logged in");
}
And this:
Connection cbconn = null;
Statement stmt2 = null;
String upcheck = "SELECT USERNAME, PASSWORD FROM USERS";
ResultSet rs = Statement.executeQuery(upcheck);
while (results.next()) {
String staffname = results.getString("snameeee");
String password = results.getString("SPwd");
if ((f.equals(staffname)) && (s.equals(password))) {
JOptionPane.showMessageDialog(null, "Username and Password exist");
}else {
//JOptionPane.showMessageDialog(null, "Please Check Username and Password ");
}
results.close();
} catch (SQLException sql) {
out.println(sql);
I guess the query should be :
Select PASSWORD from USERS where USERNAME = 'theNameInTextBox';
I have MySQL database "database" in my web. I want to connect it remotly from java. But I get Exception.
I use this code to connect it.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://site.ir:3306/database", username", "password");
Statement st = con.createStatement();
String sql = ("SELECT * FROM users ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("id");
String str1 = rs.getString("imei");
System.out.print(id+"+++"+str1);
}
con.close();
}catch(Exception e){
e.printStackTrace();
}
I think there's no problem in my code and username has All permission to access database! Please say what's problem!
Hey I am trying to verify the password matches the one they entered with the email I have been searching for the web for a few hours and everything else I have tried does not work this is what i have so far:
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) DriverManager.getConnection
(url + dbName, userName, password);
PreparedStatement checkUserInfo = (PreparedStatement) conn.prepareStatement
("SELECT password FROM profiles WHERE email = ?");
checkUserInfo.setString(1, emailT); //emailT is email pulled from an editText
//checkUserInfo.setString(2, pass1);
//Statement state = (Statement) conn.createStatement();
//String querychk = "SELECT * FROM profiles WHERE email = '"+emailT+"'";
//ResultSet rs = state.executeQuery(querychk);
ResultSet rs = checkUserInfo.executeQuery();
while (rs.next()){
String pass = rs.getString(2);
if (pass.equals(pass1)) {
return success;
}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
Simply modify your SQL Query to:
"select * from profiles where email=? and password=?"
And be-aware to validate input fields for preventing from SQL injection
And for getting PreparedStatement object or Connection object, you don't have to externally typecast it, cause it is returning the same object as you assigning to it. Even java doc also provided the below statement for the PreparedStatement
PreparedStatement pstmt = con.prepareStatement(Query);