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.
Related
I am using Java 8 and oracle.
I have confirmed that this code is working:
Statement stmt = null;
String query = "select * from custref";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String cName = rs.getString("CUSTOMER_NAME");
System.out.println(cName);
}
When I change it to this, it does not give any results:
PreparedStatement prepStmt = null;
String query = "select * from custref where CUSTOMER_NUMBER = ?";
prepStmt = con.prepareStatement(query);
prepStmt.setString(1, "12344321");
ResultSet rs = prepStmt.executeQuery();
while (rs.next()) {
String cName = rs.getString("CUSTOMER_NAME");
System.out.println(cName);
}
I have confirmed that my data type is VARCHAR hence the set string. I know my connections are fine because the basic search works just when I switch to parameterized it doesn't fail or throw exceptions it just doesn't have a result set. I have also tried the :customerNumber convention instead of the ? and this didn't work either. This is quite embarrassing but I am at my end here, nothing I can find seems to address this.
I'm learning to work with mysql database and now trying to populate statement with text from textfield.
The program is phone book and strings are name, surname and telephone number which must be writen in textfield and then added to statement for import in database.
So, for now I have this, but not working because statement dont even recognize strings as value.. any ideas what to use/write?
if("Potvrdi".equals(buttonLabel)) {
String ime = a.getText();
String prezime = b.getText();
String broj = c.getText();
Connection conn = dc.connect();
Statement st = (Statement) conn.createStatement();
st.executeUpdate("INSERT INTO imenik VALUES (ime,prezime,broj)");
conn.close();
}
Using prepare statement,
String insertTableSQL = "INSERT INTO imenik VALUES (?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertTableSQL);
preparedStatement.setString(1, ime);
preparedStatement.setString(2, prezime);
preparedStatement.setString(3, broj);
// execute insert
preparedStatement .executeUpdate();
I only clicked the button once, but the output is 2. I wonder if there is something wrong with my condition in the while loop? Or should I use a different approach?
As you can see in the picture, I entered only one data, but the output, executes the conditions in
if and else;
String pass = PF.getText();
String user = TF.getText();
Connection con = connect.getConnection();
Statement st;
ResultSet rs;
String query = "SELECT username, password FROM users";
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
if(user.equals(rs.getString(("username")))){
if(pass.equals(rs.getString(("password")))){
System.out.println("Logged In!");
}else{
System.out.println("Error");
}
}else{
System.out.println("Not in the database!");
}
}
st.close();
As per your table, you have two rows. And, you execute following query, it will return two rows.
String query = "SELECT username, password FROM users";
You could add username and password in where clause instead.
PreparedStatement stmt = connection.prepareStatement("SELECT username, password FROM users where username =? AND password=?");
stmt.setString(1, userid);
stmt.setString(2, pass);
Better use PreparedStatement to avoid any sql injection.
In below line you are selecting all the rows in users table
String query = "SELECT username, password FROM users";
You need to limit it to specific one that you want using WHERE clause.
Wikipedia about WHERE clause:
WHERE clauses are not mandatory clauses of SQL DML statements, but can
be used to limit the number of rows affected by a SQL DML statement or
returned by a query. In brief SQL WHERE clause is used to extract only
those results from a SQL statement, such as: SELECT, INSERT, UPDATE,
or DELETE statement.
Like below:
String query = "SELECT username, password FROM users WHERE username = '"+yourVariable+"' password = '"+yourVariable+"'";
I did this using String concatenation. This will lead to SQL injection. So you can use PreparedStatement as #Ravi mentioned.
Oracle doc. about PreparedStatement:
A SQL statement is precompiled and stored in a PreparedStatement
object. This object can then be used to efficiently execute this
statement multiple times.
Also this question may help you.
I've written the following code (snippet):
conn = Pooling.getDataSource().getConnection();
String databaseName = Configuration.getDatabaseName();
String sql = "SELECT * FROM " + databaseName + ".companies WHERE companyemail = ? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, username);
prepStat.setString(2, password);
System.out.println("LoginService: prepStat = " + prepStat.toString());
ResultSet rs = prepStat.executeQuery(sql);
...
Now, when I execute this, I'm getting a MySQLSyntaxErrorException. The prepStat.toString() prints:
SELECT * FROM dbname.companies WHERE companyemail = 'comp#comp.com' AND companypassword = MD5('passwort')
And a simple copy and paste to SequelPro successfully return a result.
However, the backend still claims that there is an error in the syntax:
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 '? AND companypassword = MD5(?)' at line 1
Maybee I'm blind but I do not see an error here? But what is happening here?
Okay, I found out what the problem was. I used:
ResultSet rs = prepStat.executeQuery(sql);
However, I should have used
ResultSet rs = prepStat.executeQuery();
instead.
Try this:
String sql = "SELECT * FROM '" + databaseName + ".companies' WHERE companyemail=? AND companypassword = MD5(?)";
Notice the single quote before the databaseName variable and after .companies . I think that could be the problem.
Or you could do this:
String sql = "SELECT * FROM ? WHERE companyemail =? AND companypassword = MD5(?)";
PreparedStatement prepStat = conn.prepareStatement(sql);
prepStat.setString(1, databaseName);
prepStat.setString(2, username);
prepStat.setString(3, password);
I believe the problem is at the level of parsing the databaseName to the prepared statement.
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);