ORA-04054: database link GMAIL.COM does not exist - java

I need help with my college's project(Java web with hibernate and oracle database), this has to edit the users already added previously which have:
Mail pk
pass
typeuser.iduser FK.
add and remove it works but doesnt edit, the error is :
javax.servlet.ServletException: java.sql.SQLSyntaxErrorException: ORA-04054: database link GMAIL.COM does not exist
i already tried with using prepared statement but i think i did it wrong
the mail does not need to be edited. only the type of user and password needs it but at the moment of pressing the edit button it shows me the error gmail.com does not exist
<%
//CONECTANOD A LA BASE DE DATOS:
Class.forName("oracle.jdbc.OracleDriver").newInstance();
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "C##PORTA", "oracle");
String id = request.getParameter("correo");
PreparedStatement stm = con.prepareStatement(id);
String Query = "select * from usuario where correo=" + id;
PreparedStatement ps;
ResultSet rs = stm.executeQuery(Query);
while (rs.next()) {
%>```

OldProgrammer has shown you the correct way to do this. If you use a PreparedStatement (correctly) it will deal with quoting correctly, and also protect against SQL injection attacks.
The reason you got the obscure error message was that your SQL statement most likely looks something like this after you concatenated it:
select * from usuario where correo=someone#gmail.com
Since the email address is not quoted, the SQL parser doesn't recognize that as a string literal. Instead, it is treating it as a "db link" as described in CREATE DATABASE LINK.
After you have created a database link, you can use it in SQL statements to refer to tables and views on the other database by appending #dblink to the table or view name.
And that fails because no such database link with the name "gmail.com" has been created.

You are not calling the correct methods with the correct parameters. Should be something like:
String id = request.getParameter("correo");
String query = "select * from usuario where correo= ?";
PreparedStatement stm = con.prepareStatement(query);
stm.setString(1, id );
ResultSet rs = stm.executeQuery();

Related

Search from oracle database in Java using LIKE keyword

query="select * from books where BookName LIKE \"%" +txt1.getText()+"%\"";
this is for mysql server database code.
what will be change for oracle?
DO NOT build SQL queries using string concatenation - you should be using bind parameters.
Your query string should be:
query="select * from books where BookName LIKE ?";
and then you can do something like:
Class.forName( "oracle.jdbc.OracleDriver" ); // If you are using the Oracle driver.
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:XE",
"username",
"password"
);
final String query="select * from books where BookName LIKE ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString( 1, "%" + txt1.getText() + "%" );
ResultSet rs = ps.executeQuery();
// Loop through the result set.
// Close statement/connections
(you will need to handle exceptions, etc.)
and:
You should not need to change the query to swap between MySQL and Oracle (just change the driver and connection string).
You do not need to escape any single or double quotation marks in the input string.
You are protected from SQL injection attacks.
Oracle can cache the query with the bind parameter and does not have to re-parse / re-compile it when the bind parameter changes.
If you are going to write the query as a string then string literals are surrounded by single quotes (not double quotes) in SQL:
query="select * from books where BookName LIKE '%your_string%'";
and you need to make sure that any single quotes in your string are properly escaped (but just use a bind parameter instead).
problem solved with this..
query="select * from books where BookName LIKE '%" +txt1.getText()+"%'";
thanks everyone :)

Java PreparedStatement SQL syntax error [duplicate]

This question already has answers here:
Java PreparedStatement complaining about SQL syntax on execute()
(6 answers)
Closed 6 years ago.
This is a really weird error that only started appearing today. When I use a prepared statement with ? for parameters, I get an error, but when I use it without parameters, it works just fine.
Here is the error-causing code:
String table = "files";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
PreparedStatement prep = conn.prepareStatement("SELECT * FROM ?");
prep.setString(1, table);
ResultSet rs = prep.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("file_name"));
}
This produces the following 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 ''files'' at line 1
Also, changing it to the following works just fine:
String table = "files";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
PreparedStatement prep = conn.prepareStatement("SELECT * FROM " + table);
ResultSet rs = prep.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("file_name"));
}
This doesn't seem to be making a whole lot of sense. Any ideas?
Tried it on another table and got more weired results.
This works and logs the admin in correctly:
String sql = "SELECT * FROM " + ADMIN_AUTH_TABLE + " WHERE " + column + " = '" + hashedPassword + "'";
PreparedStatement prepared = connection.prepareStatement(sql);
The following doesn't cause errors, but returns a message saying that the password entered is incorrect (it's correct - I double triple checked).
String sql = "SELECT * FROM " + ADMIN_AUTH_TABLE + " WHERE ? = ?";
PreparedStatement prepared = connection.prepareStatement(sql);
prepared.setString(1, column);
prepared.setString(2, hashedPassword);
Got it: use ? for values.
Also, the answer here helped.
Bind parameters cannot be used for identifiers in the SQL statement. Only values can supplied through bind placeholders.
This will work:
SELECT foo FROM bar WHERE id = ?
This will not work, because the table name is an identifier
SELECT foo FROM ? WHERE id = 2
You can't supply a column name, because column names are also identifiers.
A statement like this will run, but it may not do what you think it does.
SELECT ? AS foo FROM bar WHERE ? = 0
If we supply values of 'foo' for both placeholders, the query will actually be equivalent to a query containing two string literals:
SELECT 'foo' AS foo FROM bar WHERE 'foo' = 0
MySQL will run that statement, because it's a valid statement (if the table bar exists and we have privileges on it.) That query will return every row in bar (because the predicate in the WHERE clause evaluates to TRUE, independent of the contents of the table.. And we get returned the constant string foo.
It doesn't matter one whit that the string foo happens to match the name of column in our table.
This restriction has to do with how the SQL optimizer operates. We don't need to delve into all the details of the steps (briefly: parsing tokens, performing syntax check, performing semantics check, determining query plan, and then the actual execution of the query plan.)
So here's the short story: The values for bind parameters are supplied too late in that process. They are not supplied until that final step, the execution of the query plan.
The optimizer needs to know which tables and columns are being referenced at earlier stages... for the semantics check, and for developing a query plan. The tables and columns have to be identified to the optimizer. Bind placeholders are "unknowns" at the time the table names and column names are needed.
(That short story isn't entirely accurate; don't take all of that as gospel. But it does explain the reason that bind parameters can't be used for identifiers, like table names and column names.)
tl;dr
Given the particular statement you're running, the only value that can be passed in as a bind parameter would be the "hashedPassword" value. Everything else in that statement has to be in the SQL string.
For example, something like this would work:
String sqltext = "SELECT * FROM mytable WHERE mycolumn = ?";
PreparedStatement prepared = connection.prepareStatement(sqltext);
prepared.setString(1, hashedPassword);
To make other parts of the SQL statement "dynamic" (like the table name and column name) you'd have to handle that in the Java code (using string concatenation.) The contents of that string would need to end up like the contents of the sqltext string (in my example) when it's passed to the prepareStatement method.
The parameters of PreparedStatement should be applied only in parameters that can be used in conditional clauses. The table name is not the case here.
If you have a select where the table name can be applied in the conditional clause you can do it, otherwise you can not.

Problems with prepareStatement for variable table name

I have a problem with prepareStatement in my projectThe problem is that i want to query tables according to the type of user i.e if user is general then access userlist table and if user is administrator then access admin table
I have tried like :
String userid=request.getParameter("userid");
String pwd=request.getParameter("pwd");
String check = request.getParameter("radio");
String table;
String status="";
if(check.equals("General"))
table="userlist";
else
table="Administrator";
try{
String sql = "Select status from"+table+"where userid=? and pwd=?";
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/Quiz?","root","password");
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,userid);
ps.setString(2,pwd);
ResultSet rs=ps.executeQuery();
I get following exception :
Errorcom.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
'userid='nawed13593' and pwd='hello'' at line 1
I dont want to use createStatement because that will make my project prone to sql injection
Can anyone please help me solve this and the reason why the above exception was thrown?
Thank you in advance
You don't have any spaces before or after your table name. You will wind up with this, in the "Administrator" case:
Select status fromAdministratorwhere userid=? and pwd=?
Insert spaces into your SQL statement string:
// v v
String sql = "Select status from "+table+" where userid=? and pwd=?";

Using JDBC to read and update each row

I am able to read each line of a query fine, but I would also like to update a field as they are read.
The following code breaks when I add the two rs.update lines.
Connection con = DriverManager.getConnection(url, user, pass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
amount = rs.getInt("amount");
username = rs.getString("username");
rs.updateString("processed", "true");
rs.updateRow();
}
It would appear I've found my answer:
[SEVERE] com.mysql.jdbc.NotUpdatable: Result Set not updatable (referenced table has no primary keys).This result set must come from a statement that was created with a result set type of ResultSet.CONCUR_UPDATABLE, the query must select only one table, can not use functions and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details.
It won't hurt to add primary keys to my database, probably the right way to do it anyway.
I added primary key to my database and it works beautifully.
Thanks!

Java SQL "ERROR: Relation "Table_Name" does not exist"

I'm trying to connect netbeans to my postgresql database. The connection seems to have worked as I don't get any errors or exceptions when just connecting, methods such as getCatalog() also return the correct answers.
But when I try to run a simple SQL statement I get the error "ERROR: relation "TABLE_NAME" does not exist", where TABLE_NAME is any one of my tables which DO exist in the database. Here's my code:
Statement stmt = con.createStatement();
ResultSet rs;
String query = "SELECT * FROM clients";
rs = stmt.executeQuery(query);
I was thinking that netbeans might not be finding the tables because it's not looking in the default schema (public), is there a way of setting the schema in java?
EDIT: My connection code. The database name is Cinemax, when I leave out the statement code, I get no errors.
String url = "jdbc:postgresql://localhost:5432/Cinemax";
try{
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException cnfe) {
System.err.println("Couldn't find driver class:");
cnfe.printStackTrace();
}
Connection con = DriverManager.getConnection( url,"postgres","desertrose147");
I suspect you created the table using double quotes using e.g. "Clients" or some other combination of upper/lowercase characters and therefor the table name is case sensitive now.
What does the statement
SELECT table_schema, table_name
FROM information_schema.tables
WHERE lower(table_name) = 'clients'
return?
If the table name that is returned is not lowercase you have to use double quotes when referring to it, something like this:
String query = "SELECT * FROM \"Clients\"";
You could check these possibilities:
String query = "SELECT * FROM clients";
String query = "SELECT * FROM CLIENTS";
String query = "SELECT * FROM \"clients\"";
String query = "SELECT * FROM \"CLIENTS\"";
String query = "SELECT * FROM Clients";
Maybe one of those would work.
Besides CoolBeans' suggestion, you may also be connecting to the db as a different user who does not have permission on the relevant db or schema. Can you show the connection string?
Funny thing is i was experiencing the same thing as i had just started on netbeans and postgressql db, and the error was fixed after noting that the issue was that my tables in postgressql had capital letters in my naming convention which me and my jdbc query statement for INSERT was failing to find the table. But after renaming my tables in the db and fixing the column names as well am good to go. Hope it helps.

Categories