Relation "table name" doesn't exist postgresql - java

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

Related

org.postgresql.util.PSQLException: ERROR: column "id" does not exist - Java Web Service

I am developing a java web service that is deployed in wildly. It is connected to a postgresql database.
In this database, I have a table called xx_activity. In it there is a column called "id", which is also the primary key.
Here is the query used to create the table:
CREATE TABLE xx_activity
(
id serial NOT NULL,
baseitemid integer
);
to connect to this table, I use the following java code:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid" +
"from xx_activity " +
"where \"id\" = ? ");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
However, when I call the method that includes this code, I get an error:
org.postgresql.util.PSQLException: ERROR: column "id" does not exist
Position: 8
This is confusing because I certainly have this column. i added escape characters as per this answer, but it did not solve the issue.
Also note that queries without the where clause, like:
conn = postgresVoyateDBConnection();
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity");
ResultSet rs = query.executeQuery();
work perfectly.
I have also tried without using escape characters but it gives the same error. I also checked in pgadmin and there is no trailing space in the column name, neither are there any upper case letters involved (in which case, the other select query shouldn't have worked?).
How can this be fixed?
Fixed this, the issue was a missing space. After the first line of the query, there needs to be a space as belows:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where \"id\" = ? ");
EDIT: escape charactors not needed for id; so final answer should be:
query = conn.prepareStatement("select id, baseitemid " +
"from xx_activity " +
"where id = ? ");

MySql Prepared Statement to check particular table JAVA

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.

SQL search to return if several user inputs are empty

Here is my dillemma, I am trying to implement search for my website, and what I have is multiple comboboxes, and the user can select an option and press search, I do however want to at least return what exists based on their selection, i.e if they leave section blank, and only select semester, then I should have something in my result set, or if they select semester, and instructor, and leave the others blank, then I should have something in my result set, unfortunately its not working. Here is my Query.
SELECT *
FROM CoursesTaught c
WHERE c.Section = :section
AND c.CourseName=:courseName
AND c.Semester=:semeste
AND c.programName=:ProgramName
AND c.CoordinatorName=:coordinatorname
Essentially what I want to do is do a check that if empty, or "n/a" then rather than 'AND' do an 'OR' but I can't figure it out.
Probably easiest to use the union operator:
http://www.w3schools.com/sql/sql_union.asp
SELECT * FROM CoursesTaught c
WHERE c.Section = :section
union
SELECT * FROM CoursesTaught c
WHERE c.Semester=:semeste
Build your query dynamically depending on user selection. Similar question with answer how to do this in Java: How to dynamically generate SQL query based on user’s selections?
Unless you want to have a really ugly SQL query, you need to use a server side language to evaluate the user selections and build your query dynamically as a query string based on the users selection.
You can create query string manually i.e.
String query = "SELECT * FROM CoursesTaught c ";
String whereCondition = "";
if(!section.isEmpty)
if(whereCondition.isEmpty)
whereCondition = whereCondition + " AND c.Section = '" + section + "'";
else
whereCondition = "c.Section = '" + section + "'";
if(!courseName .isEmpty)
if(whereCondition.isEmpty)
whereCondition = whereCondition + " AND c.CourseName = '" + courseName + "'";
else
whereCondition = "c.CourseName = '" + courseName + "'";
.
.
.
if(!whereCondition.isEmpty)
query = query + whereCondition;
And you can pass query string to your executeQuery() method.
You'll probably see the best performance using the method suggested by Jared_S but you can do it with regular sql:
SELECT *
FROM CoursesTaught c
WHERE (c.Section = :section or :section is null)
AND (c.CourseName=:courseName or :courseName is null)
AND (c.Semester=:semester or :semester is null)
AND (c.programName=:ProgramName or :programName is null)
AND (c.CoordinatorName=:coordinatorname or :coordinatorName is null)
This assumes that the missing parameters are null, if not simply change the test to look for an empty string, assuming that's the parameter type.
One drawback to this approach is that you'll end up returning the entire table if all the parameters are null.

SQLException: Column AD not in specified tables - column AD never specified

I try to create a PreparedStatement:
stmt = conn.prepareStatement("SELECT POLBRP, POLTYP, POLNOP, INCPTP, TRMTHP, " +
"CLTKYP , CANDTP, POLSTP, EXPRYP, OINCPP, CANRNP, PAYMDP,
KCNFLP, KCRTSP, KACADP, KSCHMP, EXPRYP FROM "
+ POLHDR + " WHERE POLNOP = " + idNumber +
" AND POLBRP = " + branch + " AND POLTYP = " + product +
" AND OINCPP <= "+date );
And this throws an SQLException: [SQL0206] Column AD not in specified tables.
I have no idea where it's getting column AD from as I never specified it in the select clause (unless I'm being completely blind and stupid)
Can anyone help?
If your variables are strings, e.g. branch
" AND POLBRP = " + branch + " ...
then you forgot to quote the values
" AND POLBRP = '" + branch + "' ...
but the real solution is using placeholders
... AND POLBRP = ? ...
which would prevent such problems once and for all, this is what PreparedStatement is designed for
Try to change your query into this:
SELECT
POLBRP,
POLTYP,
POLNOP,
INCPTP,
TRMTHP,
CLTKYP,
CANDTP,
POLSTP,
EXPRYP,
OINCPP,
CANRNP,
PAYMDP,
KCNFLP,
KCRTSP,
KACADP,
KSCHMP,
EXPRYP
FROM TableName WHERE POLNOP = ? AND POLBRP = ? AND POLTYP = ? AND OINCPP <= ?";
Then use:
stmt.setString(1, "ValueOfPOLNOP");
...
When your query is being executed ? will be replaced with the value you passed into PreparedStatement#setString(int, String) method
Preventing SQL Injection in Java shows the proper use of PreparedStatement:
Prepared Statements Variables passed as arguments to prepared
statements will automatically be escaped by the JDBC driver.
Example: ps.1
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
From the same source, following in the same section:
Although Prepared Statements helps in defending against SQL Injection,
there are possibilities of SQL Injection attacks through inappropriate
usage of Prepared Statements. The example below explains such a
scenario where the input variables are passed directly into the
Prepared Statement and thereby paving way for SQL Injection attacks.
Example: ps.2
String strUserName = request.getParameter("Txt_UserName");
PreparedStatement prepStmt = con.prepareStatement("SELECT * FROM user WHERE userId = '+strUserName+'");

Problem with PrepareStatement in Java

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.

Categories