when i write database query :
select * from mytable WHERE subTitle='داتا باللغه العربيه';
it not return any thing but it is found in database table
Since you've included Java as a tag, I'll assume you're using JDBC for connecting to the database, in which case you should never be sending that particular string (SQL statement) to the database.
That is because that particular string implies string concatenation for building the SQL statement, as in:
String subtitle = "داتا باللغه العربيه";
String sql = "select * from mytable WHERE subTitle='" + subtitle + "'";
That is a very big no, no, because it leaves you vulnerable to SQL injection attacks.
Instead, you should be using a PreparedStatement and use parameters markers:
String subtitle = "داتا باللغه العربيه";
String sql = "select * from mytable WHERE subTitle=?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, subtitle);
try (ResultSet rs = stmt.executeQuery()) {
// use result set here
}
}
If this doesn't fix the character set issues you have, try using setNString instead. The 'N' is actually what you likely should have used for the string literal too, as in N'داتا باللغه العربيه', but don't use the string literal.
select * from mytable WHERE subTitle='داتا باللغه العربيه'
Related
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 question already has an answer here:
Is it possible to supply parameters for table or column name in Prepared Statements or QueryRunner.update()?
(1 answer)
Closed 7 years ago.
Are there anyway to parametrize the table in a PreparedStatement?
select * from ? where id=?
If not, what is the best approach to do that or, are there any other way to do it without loosing the advantages of a PreparedStatement?
Thanks.
The short answer is that you cannot parameterize a tablename in a prepared statement. You have to contruct the sql with string concatenation. Basically prepared statements are used for column values and not for the table names.
The best I can think of is to use string.format like this:
String sql = String.format("select * from $1%s", yourtable);
We could do in the following way
"select * from "+table_name+" where id=?";
PreparedStatement allow you to provide dynamic query parameters in where clause only
Use placeholder in place of table name and then replacing that with your tablename.
String strQuery = "INSERT INTO $tableName (col1, col2)
VALUES (?,?);";
and replace when you come to know the tablename as below:
String query =strQuery.replace("$tableName",tableName);
stmt =connection.prepareStatement(query);
String table_name= // get tablename
String sql= "select * from" +table_name+" where id=?";
If you have your PreparedStatement with an SQL query as you stated you can do:
int yourID = 1;
String tablename = "table";
String query = "SELECT * FROM " + tableName + " where id = ?";´
PreparedStatement statement = con.prepareStatement(query);
statement.setInt(1, yourID);
It will replace the ? with 1. If you have multiple ? you can set those like
statement.setString(2, "YourString");
Check
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html for more Information.
I'm searching on the web for several times but did not found anything which could help me (in java).
In fact I need to search in a sql table some rows from some reference which contains an hyphen. The issue made is that the sql replace my reference by the result of a substraction. The type of the columns are string.
Statement stmt = con.createStatement();
String query = "SELECT * FROM WAREHOUSE WHERE REF LIKE('96-18')" ;
Statement statement = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("S_FAMILY"));
}
In this code, it replaces my reference by 78 and does not naturaly return the good result.
I've searched for an escape char but did not found.
Try sending the String as parameter on the query. Doing this requires to change the Statement into PreparedStatement:
String query = "SELECT * FROM WAREHOUSE WHERE REF LIKE(?)" ;
PreparedStatement pstatement = con.prepareStatement(query,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
pstatement.setString(1, "96-18");
ResultSet rs = pstatement.executeQuery();
Note: you should send "96-18" as value of a String variable, do not hard code it.
You can try
SELECT * FROM WAREHOUSE WHERE REF LIKE('96\-18') ESCAPE '\'
Hope it helps
I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;
Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.
I am working with a Java prepared statement that gets data from an Oracle database. Due to some performance problems, the query uses a "virtual column" as an index.
The query looks like this:
String status = "processed";
String customerId = 123;
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = " + status + " AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.execute();
...
} catch (...)
This does not work. Having the function as part of the where clause causes a SQLException. I am aware of CallableStatement, and know I could use that first and then concatenate the results. However, this table uses FN_GET_CUST_ID(trans_id) as part of it's index. Is there a way to use a prepared statement with a database function as a query parameter?
Never concatenate arguments for the SQL into the String. Always use placeholders (?) and setXxx(column, value);.
You'll get the same error if you'd run the SQL in a your favorite DB tool. The problem is that Oracle can't use the function for some reason. What error code do you get?
If Customer ID is numeric keep in int not in String. Then try doing the following:
String query = "SELECT DISTINCT trans_id FROM trans WHERE status = ? AND FN_GET_CUST_ID(trans.trans_id) = ?";
ps = conn.prepareStatement(query);
ps.setString(1, status);
ps.setInt(2, customerId);
ps.execute();
Besides other benefits of prepared statement you won't have to remember about string quotations (this causes your error most likely) and escaping of the special characters.
At the first glance, the query seems to be incorrect. You are missing an apostrophe before and after the usage of status variable (assuming that status is a varchar column).
String query = "SELECT DISTINCT trans_id FROM trans
WHERE status = '" + status + "' AND FN_GET_CUST_ID(trans.trans_id) = " + customerId;
EDIT: I am not from java background. However, as #Aron has said, it is better to use placeholders & then use some method to set values for parameters to avoid SQL Injection.