Hi i have a small problem, how do i switch tables to get results from??
The code below is not working.However that should give you some idea of what i am trying to do.
Thanks for the help
String typelogin=null;
if(xx){
typelogin="users_table";
}else{
typelogin="admin_table";
}
String sqlStr = "Select * from "+typelogin+" where username=? and userpassword=?";
PreparedStatement stmt = conn.prepareStatement(sqlStr);
The full code:
Statement stmt = conn.createStatement();
String sqlStr = "Select * from "+typelogin+" where username=? and userpassword=?";
PreparedStatement pstmt=conn.prepareStatement(sqlStr);
pstmt.setString(1,user);
pstmt.setString(2,password);
//step 6 Process result
ResultSet rs = pstmt.executeQuery();
The error i am getting:
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 'fromspmovy_admin where username='abc' and userpassword='abc'' at line 1
Answer[SOLVED]:
forgot to put white space
from " + typelogin + " where
From your error message: 'fromspmovy_admin where ... looks like you missed a whitespace between from and your table name. Make sure you're doing this in the right way in all your methods (note that in your current example this won't happen).
If you will use ? for pass the variables, you must use PreparedStatement not Statement. Also according your error message you need to add a white space after from (check fromspmovy_admin)
Related
As I'm finding my way slowly in Java , I'm facing a runtime error when my program is executed..
I'm doing this coding in a select statement …
i get an error code that using "?" this way is not accept in MariaDB syntax!!
How to solve this issue ….
note that UserName is defined as avariable in the prog.
Thanks
Here's my Code:
String sql = "select Username , Userpassword from Users where Username where Username = ?";
statement = con.prepareStatement(sql);
statement.setString(1, UserName);
statement.executeQuery(sql);
while (statement.getResultSet().next()){
// ...
where Username where Username = ?
Your SQL query is invalid. You have a where clause twice.
Your code has two problems that I can see. First, as #Michael pointed out, you have two WHERE clauses. Maybe this is just a copying error, or maybe this is verbatim what your code is. In either case, it's wrong, and your query should have just one WHERE clause. The other problem is that you are making the following call to execute the query:
statement.executeQuery(sql);
PreparedStatement#executeQuery does not take any parameters; just call it with no parameters. So here is the suggestion I would make for you:
String sql = "SELECT Username, Userpassword FROM Users WHERE Username = ?";
statement = con.prepareStatement(sql);
statement.setString(1, UserName);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
// process a row
}
Getting error in Select from MYSQL on the line ResultSet rs = st.executeQuery(fetch_title);
Error msg : 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 ':09:53' at line 1
String test = "27-May-2016 11:09:53";
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time="+test+"";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(fetch_title);
Wrap up your date in speech marks in the query.
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time='"+test+"'";
You have to declare the string in your MySQL query as a string; you aren't doing this which results in the error.
So you need to insert in '' in your case.
So you could do it like this:
String fetch_title = "SELECT title FROM competitor_analysis WHERE cron_date_time='"+test+"'";
Your code is unsafe because it is conducive to SQL Injection attacks, you need to use a PreparedStatement instead as next:
String test = "27-May-2016 11:09:53";
PreparedStatement ps = connection.prepareStatement(
"SELECT title FROM competitor_analysis WHERE cron_date_time=?"
);
ps.setString(1, test);
ResultSet rs = ps.executeQuery();
This approach has 2 main advantages:
It is safer as mentioned above
It is less error prone, as you don't have to escape the value explicitly anymore since it will be managed by the driver itself
here is the code there is catch close but i delete it so can anyone replay to me
String id = null;
String root="root",student="root";
String name=jTextField1.getText();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection
con=(Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306
/dijlafinal1",root,student);
String query2="SELECT * FROM name WHERE name like ? ";
PreparedStatement pstm2=null;
pstm2=con.prepareStatement(query2);
pstm2.setString(1,"%"+name+"%");
ResultSet rs = pstm2.executeQuery(query2 );
while (rs.first()){
String name1=rs.getString("name");
id= rs.getString("id");
int epo =rs.getInt("epo");
}
jTextField2.setText(id);
}
You need to use the no-argument version of executeQuery(), i.e.
ResultSet rs = pstm2.executeQuery();
The reason is that you've already prepared the statement when you called con.prepareStatement(query2). Calling executeQuery(query2) will throw away the prepared SQL and execute the query without bind variables, leaving the ? in place -- as the error message suggests.
When working with a PreparedStatement you always call the .execute... methods without any arguments because you have already supplied the SQL command text with the .prepareStatement call. So
ResultSet rs = pstm2.executeQuery(query2 );
is incorrect. You need to simply do
ResultSet rs = pstm2.executeQuery();
I wonder if it might work if you use this?
pstm2.setString(1,"'%"+name+"%'");
When I use the following code it runs perfectly.
PreparedStatement st = con.prepareStatement("select * from users where username=?");
st.setString(1, userId);
ResultSet rs = st.executeQuery();
But when I am using the following code, I get an error that userId (that I pass as parameter) is an invalid column name.
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where username="+userId);
Why statement method doesn't work and I have to use PreparedStatement?
User ID is a string (SQL calls this type CHAR or VARCHAR), it must be put in quotes if used in the SQL requests. Like this:
select * from users where username='12345'
PreparedStatement is much better solution because of the SQL injection. You CANNOT just write:
ResultSet rs = st.executeQuery("select * from users where username=\""+userId+"\"");
WRONG CODE - ^^^^^^^^^^^^^^^
because user ID can contains control characters like ['], ["] or [\]. It depends on the SQL server and sometimes are more sophisticated than it looks like. If using PreparedStatement, it is automatically managed by the JDBC driver.
First of all, is better to use the first one. But if you really want to use the second one, you need to put your value into quotes. Simple add the quotes to the value. But is good to create a function to it, if you are going to use it a loot. Like:
public String doubleQuoted(String value){
return "\"" + value + "\"";
}
or
public String singleQuoted(String value){
return "'" + value + "'";
}
and use
ResultSet rs = st.executeQuery("select * from users where username="+singleQuoted(userId));
You need to put strings into quotes:
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where username=\'"+userId+"\'");
\ is the escape character.
Note:
Your prepared statement is the preferred way of handling SQL queries. See #30thh answer as to why (SQL Injection attacks).
This is the whole message I receive:
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 ''user','age','school','password') values ('Admin','22','tei','admin')' at line 1
And this is the code:
String user = textField.getText().trim();
String age = textField_3.getText().trim();
String school = textField_4.getText().trim();
String password = String.valueOf(passwordField.getPassword());
String password1 = String.valueOf(passwordField_1.getPassword());
if(password.equals(password1)){
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
PreparedStatement st = con.prepareStatement("insert into user ('user','age','school','password') values ('"+user+"','"+age+"','"+school+"','"+password+"')");
int rs = st.executeUpdate();
JOptionPane.showMessageDialog(frame, "Data Saved Successfully");
Any ideas?
The point of prepared statements is, among others, to not concatenate your queries yourself.
You want to do the following:
//first you "prepare" your statement (where the '?' acts as a kind of placeholder)
PreparedStatement st = con.prepareStatement("insert into user (user,age,school,password) values (?,?,?,?);");
//now you bind the data to your parameters
st.setString(1, user);
...
//and then you can execute it
st.executeUpdate()
For more details see the official tutorial.
There are a couple of things happening behind the scenes that make the query safe, like escaping special characters that would otherwise allow altering the statement (google SQL injections if you want to know more)