I have asked this beacause i was not able to find the answer.
what i am doing is
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE diseaseName =""+diseaseName +'" AND name = '"+username+"'";
it is perfecty running unless and until diseases does not contain 's type of word like
Wilms' tumor
Addison's disease
etc....
so query like
SELECT * FROM diseaseinfo WHERE diseaseName = 'Adult Still's disease' AND name = 'add';
wont execute because of ' 's on 'Adult Still's
and also in java i cant start string with String selectTableSQL = ' '; it will always be in String selectTableSQL = " ";
any solution?
To avoid this case and any syntax error or SQL Injection you have to use PreparedStatement instead :
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE col1 = ? and col2 = ?";
try (PreparedStatement ps = connection.prepareStatement(selectTableSQL)) {
ps.setString(1, value_1);
ps.setString(2, value_2);
ResultSet rs = ps.executeQuery();
while(rs.next()){
//...
}
}
The correct way to use queries in JDBC is to use PreparedStatement and bind variables.
But in your case, try replacing the single quotes ' in your values with \'.
You can use a simple diseaseName.replace("'", "\\'"); to do it.
Related
Lets say I have this table:
CREATE TABLE T (col varbinary(100));
Now I would like to do a "LIKE" query on this column using java, something like this -
String query="SELECT * from T WHERE col LIKE ?";
PreparedStatement st = connection.prepareStatement(query); // Assuming I already have connection object
byte[] prefixBytes = somePrefixBytesIWouldLikeToSearchFor;
String likeString = new String(bytes) + "%";
st.setString(1, likeString);
st.executeQuery();
Is that right way to go about it? If not, what is the correct way. Thanks.
You could use string concat inside sql command eg:
String query="SELECT * from T WHERE col LIKE concat(?, '%')";
PreparedStatement st = connection.prepareStatement(query); // Assuming I already have connection object
byte[] prefixBytes = somePrefixBytesIWouldLikeToSearchFor;
String likeString = new String(bytes)
st.setBytes(1, bytes);
st.executeQuery();
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='داتا باللغه العربيه'
I keep getting this error when trying to connect to the database.
This is my prepared statement
String SQL = "SELECT * FROM `?` WHERE `HomeTeam` = '?'";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box1.getSelectedItem().toString());
rs = prepst.executeQuery();
Anyone know why I get this error?
I think that your problem is in ' and ``` symbols. You should fix the sql as follwing:
String SQL = "SELECT * FROM ? WHERE HomeTeam = ?";
However I am not sure that parameter placeholder ? is supported after from. So, propbably you will have to put it yourself, e.g.:
String table = box1.getSelectedItem().toString();
String SQL = "SELECT * FROM " + table + " WHERE HomeTeam = ?";
Use
String SQL = "SELECT * FROM ? WHERE HomeTeam = ?";
Don't use ` to nest parameters, use ' to nest values you're comparing against if you're hard coding them.
You can't use ? to specify a table name.
how would i write this sql statement without a hard coded value?
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name = 'john'");
// this works
rather have something like:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + name);
// Unknown column 'john' in 'where clause' at
// sun.reflect.NativeConstructorAccessorImpl.newInstance0...etc...
thanks in advance..
It is a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
Note that prepareStatement() is an expensive call (unless your application server uses statement caching and other similar facilities). Theoretically, it'd be best if you prepare the statement once, and then reuse it multiple times (though not concurrently):
String[] names = new String[] {"Isaac", "Hello"};
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");
for (String name: names) {
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
...
...
statement.clearParameters();
}
You are missing the single quotes around your string, your code corrected:
String name = "john";
String sql = "select * from myDatabase.myTable where name = '" + name + "'";
// Examine the text of the query in the debugger, log it or print it out using System.out.println
resultSet = statement.executeQuery(sql);
Print out / log text of the query before executing the query to see if it looks OK.
If you are going to do a lot of similar queries where only the constant changes, consider using prepared statements
this should work:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + "'" + name + "'");
you need to put quotes around the value ('john' instead of john)...
Try the following :
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where myTable.name = '" + name + "'");
Put quotes around your name value since it's a string.
"select * from myDatabase.myTable where name ='" + name + "'"
Example query:
SELECT country
FROM data
WHERE city LIKE
(SELECT LEFT ('jakartada',7));
Example in JDBC:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('?',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Why this doesn't work properly?
There is no parameter within the prepared statement, however the code attempts to set a parameter. Try adding a parameter to the statement.
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT (?,7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Or try removing the statement setting the parameter:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('jakartada',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
I believe you're making this harder than it needs to be, and at the same time you're missing something. Is this what you're trying to do?
SELECT country FROM data WHERE city LIKE 'jakarta%'
That is, are you looking for the country column from every row where the city name starts with 'jakarta'? If so, don't forget the % sign. If you don't include the % sign, then
SELECT country FROM data WHERE city LIKE 'jakarta'
and
SELECT country FROM data WHERE city = 'jakarta'
mean exactly the same thing as each other, and the LIKE operator is pointless; you may as well use the = operator.
So, it seems to me the MySQL query you want is
SELECT country FROM data WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
to add the % sign. You don't need the subselect in this case.
Like you pointed out, the Java code you need then is:
String sql = "SELECT country FROM data " .
"WHERE city LIKE CONCAT(LEFT(?,7),'%')";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
... process the rs records ...
rs.close(); /* please don't forget to close your result sets */
use this link for your solution and this query
http://sqlfiddle.com/#!2/c79ab/10
SELECT country FROM data
WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
Don't you quotes in your prepared statement when setting values at runtime... Otherwise it will take it as input only not for ps position... Remove single quotes from your question mark...