I am trying to query a MS Access database from my java code and I am having no luck with the % wildcard that I read should work in other posts. The LIKE operator works if I exclude the wild cards from my code and provide the searchText variable with a value that matches exactly to a records Description. Below is the String queries I have tried that have either returned null or an exception:
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '%" searchText + "%' ORDER BY [WorkOrderNo] DESC", tableName);
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '*" searchText + "*' ORDER BY [WorkOrderNo] DESC", tableName);
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \"%" searchText + "%\" ORDER BY [WorkOrderNo] DESC", tableName);
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \'%" searchText + "%\' ORDER BY [WorkOrderNo] DESC", tableName);
Any help is greatly appreciated.
The percent sign (%) is definitely the right wildcard character to use in this case. For test data
ID Description
-- -----------------------------------
1 I like apple pie.
2 This is a test.
3 Apple makes iThings.
4 This is another test.
5 Name of a tropical fruit: pineapple
the code
String tableName = "SSPWO";
String desc = "[Description]";
String searchText = "apple";
PreparedStatement ps = con.prepareStatement(
String.format("SELECT * FROM %s WHERE %s LIKE ?", tableName, desc)
);
ps.setString(1, "%" + searchText + "%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(String.format("%d: %s", rs.getInt(1),rs.getString(2)));
}
produces the following console output
1: I like apple pie.
3: Apple makes iThings.
5: Name of a tropical fruit: pineapple
You've got a whack of syntax errors anyways:
String query = String.format([..snip...] + " LIKE '%" searchText
^---missing +
Related
I am building an App and dealing with databases for the first time I am trying to get the data TEXT as input and search its match in the specific row. I have failed to do that.
I have got the specific row selected. I have six columns and I have got the specific row depending upon the id but comparing the Input Text in the other five columns is giving problematic output.
With my approach given in the code below it is giving results after comparing it with the first or last column entry but not all.
public Cursor finddata(String name,int ida, int guess){
String Query = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME1='" +name+ "'";
cursor=db.rawQuery(Query,null);
check=1;
if(cursor==null){
String Query2 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME2='" +name+ "'";
cursor=db.rawQuery(Query2,null);
check=2;
}
if(cursor==null){
String Query3 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME3='" +name+ "'";
cursor=db.rawQuery(Query3,null);
check=3;
}
if(cursor==null){
String Query4 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME4='" +name+ "'";
cursor=db.rawQuery(Query4,null);
check=4;
}
if(cursor==null){
String Query5 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME5='" +name+ "'";
cursor=db.rawQuery(Query5,null);
check=5;
}
if(cursor==null){
String Query6 = "SELECT NAME1 FROM Capital_Names where ID = '" + ida + "' and NAME6='" +name+ "'";
cursor=db.rawQuery(Query6,null);
}
return cursor;
}
I think there is some error in the if condition that I am applying on the cursor as
"if(cursor==null)" because it is only giving the answer by comparing the first statement without if even if it is matching in the first statement or not.
If there is some direct query statement to do that ?????
I have searched a lot on the internet but could not find a solution.
And please do not direct me to already answered questions and answer this question if you could.
Regards
What you are doing wrong is that you check if the Cursor object returned by rawQuery() is null.
rawQuery() returns a Cursor which may be empty (without any rows) but it can never be null.
You can check if there any rows in the Cursor by checking its moveToFirst() method.
Also never use concatenation of the parameters of the sql statement. It is not safe.
Use placeholders ? and the 2nd argument of rawQuery() to pass the parameters.
So change to this:
public Cursor finddata(String name, int ida, int guess){
String sql = "SELECT NAME1 FROM Capital_Names " +
"WHERE ID = ? AND ? IN (NAME1, NAME2, NAME3, NAME4, NAME5)";
return db.rawQuery(sql, new String[] {ida, name});
}
It seems in your code that you don't use the argument guess of finddata(), so you can remove it.
Also are you sure that you want to return only the column NAME1? You can replace it with "SELECT * FROM..." to return all the columns.
public Cursor finddata(String name,int ida, int guess){
String Query = "SELECT NAME1 FROM Capital_Names
WHERE ID = '" + ida + "'
AND
(
NAME1='" +name+ "' OR NAME2='" +name+ "' OR NAME3='" +name+ "' OR
NAME4='" +name+ "' OR NAME5='" +name+ "')"
;
return db.rawQuery(Query,null);
}
Try this on...
Here I get the last value of pushkey(column) by below code
String abc="value for filtering data"
String selectQuery= "SELECT * FROM " + TABLE_NAME+" ORDER BY id DESC LIMIT 1";
SQLiteDatabase db = myDbHandler.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String str = "";
if(cursor.moveToFirst())
str = cursor.getString( cursor.getColumnIndex(COLUMN_PUSH_KEY) );
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
cursor.close();
But now I want to get last value of pushkey when fromid(column) set filter by some predefined String abc value. So how to add filter and make query ?
https://i.stack.imgur.com/77thU.png
If by last you mean ordered by ID descending then add a WHERE clause like this:
String selectQuery= "SELECT pushkey FROM " + TABLE_NAME + " WHERE fromid = 'DIX....UVa2' ORDER BY id DESC LIMIT 1"
If you just want to filter by fromid:
String selectQuery= "SELECT pushkey FROM " + TABLE_NAME + " WHERE fromid = 'DIX....UVa2'"
If you want all the columns, change to:
String selectQuery= "SELECT * FROM " + TABLE_NAME + " WHERE fromid = 'DIX....UVa2'"
Use this Java code:
String fromid = "DIX....UVa2";
String selectQuery= "SELECT * FROM " + TABLE_NAME + " WHERE fromid = ?";
SQLiteDatabase db = myDbHandler.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, fromid);
String str = "";
if(cursor.moveToFirst())
str = cursor.getString( cursor.getColumnIndex(COLUMN_PUSH_KEY) );
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
cursor.close();
Replace "DIX....UVa2" with the value that you want to filter the column fromid.
This will toast the 1st value of the results.
I'm trying to make a prepared statement and the drivers are working how I assume they are supposed to but the only problem is that my query is no longer valid.
I'm trying to write this query:
SELECT ip_address
FROM log_activity
WHERE created_at
BETWEEN "2017-01-01 00:00:00"
AND DATE_ADD("2017-01-01 00:00:00", INTERVAL 1 HOUR)
GROUP BY ip_address
HAVING COUNT(*) > 200;
But after inserting the parameters for the prepared statement it comes out as:
SELECT ip_address
FROM log_activity
WHERE created_at
BETWEEN '\'2017-01-01 00:00:00\''
AND DATE_ADD('\'2017-01-01 00:00:00\'', INTERVAL 1 'hour')
GROUP BY ip_address
HAVING COUNT(*) > 200;
Which is no longer valid SQL. So how do I remove these quotations from the parameters or what is a good way to work around this?
...
String startDateArg = "'" + args[0].split("=", 2)[1].replace(".", " ") + "'";
String durationArg = args[1].split("=", 2)[1];
int thresholdArg = Integer.parseInt(args[2].split("=", 2)[1]);
String duration = durationArg.equals("hourly") ? "hour" : durationArg.equals("daily") ? "day" : null;
String getUsersOverAPILimitQuery = "" +
"select ip_address " +
"from log_activity " +
"where created_at " +
" between ?" +
" and date_add(?, interval 1 ?) " +
"group by ip_address " +
"having count(*) > ?;";
PreparedStatement preparedStatement = con.prepareStatement(getUsersOverAPILimitQuery);
preparedStatement.setString(1, startDateArg);
preparedStatement.setString(2, startDateArg);
preparedStatement.setString(3, duration);
preparedStatement.setInt(4, thresholdArg);
System.out.println(preparedStatement);
ResultSet getUsersOverAPILimit = preparedStatement.executeQuery();
while (getUsersOverAPILimit.next()) {
String ip_address = getUsersOverAPILimit.getString("ip_address");
System.out.println(ip_address);
}
...
Instead of this:
String startDateArg = "'" + args[0].split("=", 2)[1].replace(".", " ") + "'";
Do this:
String startDateArg = args[0].split("=", 2)[1].replace(".", " ");
no need to add in the single quotes, the preparedstatement does it for you.
I am developing an application that can update my database... However, I can't get my Java method working correctly. It gives me the following error: Must declare the scalar variable "#P0WHERE". Any suggestions?
The method I am using:
public void updateTable() throws SQLException
{
Scanner input = new Scanner(System.in);
System.out.println("Update the following:\n" + this);
this.getReservationInfo(input);
DataConnection connection = new DataConnection();
String query = "UPDATE " + TableName;
query += "Set Name = ?";
query += "WHERE Person_ID = " + id;
connection.updateData(query, person_name);
connection.closeConnection();
}
Add spaces before 'SET' and 'WHERE', otherwise it will not work.
String query = "UPDATE " + TableName;
query += " SET Name = ?";
query += " , Age = ?";
query += " , Col1 = ?"; //And other cols
query += " WHERE Person_ID = " + id;
EDIT: Changed query to update multiple columns.
I think so. You seem to be missing spaces. After the TableName and after the ?.
String query = "UPDATE " + TableName;
query += " Set Name = ?"; // tableSet not good, and
// ?WHERE is not valid add spaces.
query += " WHERE Person_ID = " + id;
I have sql code in java class. The code is just like this below.
private void SummTEkspor(){
try {
bln = (String) cmbBln.getSelectedItem();
thn = (String) cmbThn.getSelectedItem();
String sql1 ="DELETE FROM a.dbo.t_export";
String sql2 ="INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn;
Statement st = kon.conn.createStatement();
int rs = st.executeUpdate(sql1);
int rsl = st.executeUpdate(sql2);
} catch (Exception x) {
System.out.println("FAILED");;
}
}
when i run the sql1, it works, but when sql2, it did not work properly, and just display FAILED . I guess the query in sql2 didn't take any value from what selected combo box. How can i solve that? Thanks for any reply
The problem is because you query is not proper :
INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn;
When you are creating a second select sub-query, you have not closed the ) bracket.
Try this :
INSERT INTO a.dbo.t_export" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN " +
"(SELECT sk_batch from batch_hdr WHERE bln_proses='"+bln+
"' AND thn_proses='"+thn + "')";
You open a bracket in (SELECT sk_batch f and never close it.
Use System.out.println(sql2); in order to see how the second query looks like, it could also be that one of the parameters thn and bln are null for example.
Fix the Query, quote the string values and put proper spaces.
String bln="testing";
String thn="abc";
String sql2 ="INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses='"+bln+
"' AND thn_proses='"+thn+"')";
Maybe there are som ereasons:
- closing braket in second select statement
- if bln_proses or thn_proses are strings then you have to use ' character to encompass the values
First of all you have put \n in your queries which is unnecessary, then Qualifying the table a.dbo.t_export is not needed.
Instead of:
String sql2 ="INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn;
Try:
String sql2 ="INSERT INTO dbo.t_export " +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN " +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
" AND thn_proses="+thn +")";
If your columns are of Varchar type then you have to put values inside '' (Single Quotes).
Above query will work. But I suggest you to not use this approach because there is a chance of SQL Injection. Use Precompiled statements to avoid SQL Injection.
Try this query
String sql2 ="INSERT INTO a.dbo.t_export" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN " +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn+ ")";
bln_proses & thn_proses these are from same table batch_hdr ???