I can use # in mysql. But I can't use # in java(jdbc). Could you give some advice?
mysql (working very well)
select ssn from (select * from EMPLOYEE)EMPLOYEE_sorted,(select
#pv='888665555') initialisation where find_in_set(superssn,#pv) and length(#pv
:= concat(#pv,',',ssn));
java (jdbc) doesn't work
String query = "select ssn from (select * from EMPLOYEE)EMPLOYEE_sorted,
(select #pv=888665555) initialisation where find_in_set(superssn,#pv) and length(#pv := concat(#pv,',',ssn))"
To set this you may create a PreparedStatement and assign ‘?’ wherever you want to place the #xxxxxx.
To set the values inside the ‘?’ you have to use the command
setString()/setInt()/set<variable>();
This is more clear when I show you an example.
PreparedStatement p = con.prepareStatement("select * from people where
(first_name = ? or last_name = ?) and address = ?");
p.setString(1, name);
p.setString(2, name);
p.setString(3, address);
Here is the link to the sample.
Related
Got a question, how can i get 2 different variables from different tables using mysql? Is it possible to make it work from 1 query using prepared statement? I'm new at mysql database programming with java, so that's my problem.
I'm trying to get:
user_key from user table
project_key from project table
and yes, I know, table names should be in non singular form.
I'm trying :
String project_key = null;
String user_key = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://mysql:" + Config.getPortDB() + "/" + Config.getDatabase() + "?"
+ "user=" + Config.getUsername() + "&password=" + Config.getPassword());
String query ="SELECT user_key,project_key FROM user, project WHERE user_key = ? AND project_key = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
for(int i = 0; i < auths.size() ; i++ ) {
preparedStatement.setString(i+1, auths.get(i));
}
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
project_key = rs.getString("project_key");
user_key = rs.getString("user_key");
}
System.out.println(project_key); // null
System.out.println(user_key); // null
What am I doing wrong here?
SELECT u.user_key,
p.project_key
FROM (select user_key from user WHERE user_key = ?) u,
(select project_key from project WHERE project_key = ?) p
If the tow tables has no relation at all you still can get the 2 values using subqueries
This is your current query:
SELECT user_key,project_key
FROM user, project
WHERE user_key = ?
AND project_key = ?
To get results from 2 tables use JOIN, like this:
SELECT u.user_key, p.project_key
FROM user u
JOIN project p ON p.userId = u.id
WHERE u.user_key = ?
AND p.project_key = ?
I wonder if there is a way to select table with user input in the following statement:
myStmt = db.myConn.prepareStatement("select * from Rooms where "
+ "idRooms = ?");
myStmt.setInt(1, roomNum);
myRs = myStmt.executeQuery();
Is there a possibility to do something like select * from =? where idRooms = ? to select Rooms with prepared statement upon user input?
myStmt.setString(1, Room);
mysStmt.setInt(2, roomID);
Thanks
It is not possible to add a table name as a parameter.
You can simply create a string containing your constructed query as follows:
String query = "select * from " + userParamVariable + " where idRooms = ?"
I guess you manage your tables with splitting, but unfortunately PreparedStatement does not support it, you can manually replace the table name with String.format() method.
Hi I'm doing a query in java, i have java and posgres connected with the driver 9.3-1102-jdbc41
This is my query: query = "SELECT * FROM" +"\"users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
when I run it, this error appears:
Relation "users name" doesn't exist
Here and in others sites a possible solution is checking the quotes or the capital letters.
But I´m sure about the capital letters and this is what I tried:
query = "SELECT * FROM" +"\"users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
query = "SELECT * FROM users where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
query = "SELECT * FROM" +"\"sysmar.users\" "+ " where user="+"'"+name+"'"+"and pass =" +"'"+pass+"'";
Error relation users does not exist
"SELECT * FROM users where user="+name+"and pass =" +pass;
syntax error near to pass
Thanks in advance for your answers and time
try:
"SELECT * FROM users where \"user\" ='"+name+"'and pass ='" +pass+"'";
But it's harmful for sql injection. See PreparedStatements.
For PostgreSQL you shouldn't need to put quotes around the table name unless it's a reserved keyword. Users isn't a keyword, but user just so happens to be one of them.
Your query is hard enough to read with the extra concatenation operations and spacing issues. Perhaps there is a syntax error and you just need to clean it up:
q = "SELECT * FROM users WHERE \"user\" = '" + name + "' AND pass = '" + pass + "'";
You want the final evaluated string to look like (for example):
SELECT * FROM users WHERE "user" = 'cory' AND pass = '12345';
But as others have mentioned, you should also switch to using prepared statements. This code is probably vulnerable to SQL injection attacks.
You really shouldn't concatenate variables with SQL queries, you are becoming vulnerable to SQL injection then. You better be using Prepared Statements which will allow you to write queries in more readable and secure fashion.
Connection conn = DriverManager.getConnection(...);
String queryString = "SELECT * FROM users WHERE user = ? AND pass = ?";
PreparedStatement query = conn.prepareStatement(queryString);
query.setString(1, name);
query.setString(2, password);
ResultSet result = query.executeQuery();
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= !;";
query = query.replace("?", "'"+post.getDatetime()+"'");
query = query.replace("!", Integer.toString(post.getPublisher().getID()));
PreparedStatement pstm = con.prepareStatement(query);
ResultSet rs = pstm.executeQuery();
The resulting query looks like this
SELECT * FROM POST_COMMENT WHERE Post_date_time= '2013-04-12 07:20:34.0' AND Post_User= 378;
Which works right in the MySQL prompt line but, when launched from prepared statement throws this error:
Exception in thread "main" 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 '07:20:34.0 AND Post_User=378' at line 1
But
pstm.setString(1, post.getDatetime());
pstm.setString(2, Integer.toString(post.getPublisher().getID()));
isn't working either.
Table definition
CREATE TABLE Post_Comment (
Comment_ID INTEGER(7) NOT NULL,
Post_date_time DATETIME NOT NULL,
Post_User INTEGER(7) NOT NULL,
PRIMARY KEY(Comment_ID, Post_date_time, Post_User),
CONSTRAINT Post_Comment_Post
FOREIGN KEY (Post_User, Post_date_time)
REFERENCES Post (User, date_time)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT Post_Comment_Comment
FOREIGN KEY (Comment_ID)
REFERENCES Commentary (ID)
ON DELETE CASCADE
ON UPDATE CASCADE
)
;
Please help.
Take a look at the Java tutorials. You're not supposed to replace() the fields using the String functions.
You're supposed to call the "set" methods of the PreparedStatement.
EDIT:
No, take a look at the available methods. And what types the database columns expect. If you want a date, use setDate(), if you want an Integer, then use setInt(). Example:
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time = ? AND Post_User = ?;";
PreparedStatement pstm = con.prepareStatement(query);
pstm.setDate(1, post.getDatetime());
pstm.setInt(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();
Also note that the query uses ? for both placeholders, not !.
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= ?;";
PreparedStatement pstm = con.prepareStatement(query);
pstm.setObject(1, post.getDatetime());
pstm.setObject(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();
I have created table with 3 fields language,country,install type. When I write a query to print the maximum occuring value in each of the field, I am getting a weird problem.Can anyone say the reason.Here is my code.
PreparedStatement ps1= null;
ps1 = conn.prepareStatement("desc Configuration");
ResultSet rs1=ps1.executeQuery();
while(rs1.next()) {
System.out.print(rs1.getString(1)+":");
PreparedStatement ps2= null;
ps2 = conn.prepareStatement("select ? from Configuration c1 "+
" group by language "+
" having count(*) >= all " +
" ( select count(*) from Configuration c2 "+
" group by language )");
ps2.setString(1,rs1.getString(1));
ResultSet rs2=ps2.executeQuery();
while(rs2.next())
System.out.print(rs2.getString(1));
System.out.println();
}
The output I am getting here is language:language But the output what I am expecting is
language:english like that. I am getting later output if i replace '?' with language in the prepare statement.But if i give the same with ? I am getting what ever I have given for ps2.setString.
Why is this happening. Any solutions?
? in prepared statements is not a placeholder for textual substitution, it's a parameter, therefore its value is always interpreted as data, not as an arbitrary part of query syntax.
So, in this case the actual query being executed is an equivalent of select 'language' from ....
If you need to substitute parts of the query other than data, you have to use concatenation (beware of SQL injections!):
ps2 = conn.prepareStatement("select "
+ rs1.getString(1)
+ " from Configuration c1 group by language having count(*) >= all( select count(*)from Configuration c2 group by language )");
You can't set column names using a PreparedStatement. You can only set column values.
Instead of using this approach, you will have to build the sql yourself using concatenation, for example:
String sql = "select "+ rs1.getString(1) + " from Configuration c1 group by language having count(*) >= all( select count(*)from Configuration c2 group by language)";
The '?' mark in ps2 is recognized as literal-string. Not as a column name.