sqlite-net query with parameter that contains multi instructions - sql

I have a table with lots of information and now I want that a user can search that table.
List<Table> tableSearch = new List<Table>();
string[] words = searchString.Split(' ');
string sqlSearch = "";
foreach (string word in words)
{
sqlSearch += " and Searchstring LIKE "+ "'%" + word + "%'";
}
tableSearch = db.Query<Table> ("select * from Table WHERE 1 = 1" + sqlSearch);
This is working and the solution I want to get to.
The problem is, that when the searchString is something like Dü, D' I get an exception.
I found here sqlite-net like statement crashes a good solution for the problem.
My problem is, that the only solution I found for now is something like:
if (words.Length < 2)
tableSearch = db.Query<Table> ("select * from Table WHERE Searchstring LIKE ?", "%" + words[0] + "%");
else if (words.Length < 3)
tableSearch = db.Query<Table> ("select * from Table WHERE Searchstring LIKE ? and Searchstring LIKE ?", "%" + words[0] + "%", "%" + words[1] + "%");
and so on......
but this is not the solution I want.
Someone got an Idea?

You need to replace the special characters that makes an error in SQL string
For example the ' character need to be replaced with '' in SQL string. So, we need to modify your code to be like that.
List<Table> tableSearch = new List<Table>();
string[] words = searchString.Split(' ');
string sqlSearch = "";
foreach (string word in words)
{
sqlSearch += " and Searchstring LIKE "+ "'%" + word.Replace("'", "''") + "%'";
}
tableSearch = db.Query<Table> ("select * from Table WHERE 1 = 1" + sqlSearch);
To know more about how to escape special characters please refer to the following link
How does one escape special characters when writing SQL queries?

I cant offer advice about the issue where the accented "Du" is concerned, but D' causes an error because the ' isnt escaped, and it interferes with the sql; accordingly in your first code block,
replace
sqlSearch += " and Searchstring LIKE "+ "'%" + word + "%'";
with
sqlSearch += " and Searchstring LIKE '%" + word.Replace("'","''") + "%'";

Here's another way of writing N.Nagy 's answer, with less string joins:
var words = (IEnumerable<string>)searchString.Split(' ').ToList();
const string SqlClause = "Searchstring LIKE '%{0}%'";
words = words.Select(word => string.Format(SqlClause, word.Replace("'", "''")));
var joined = string.Join(" AND ", words.ToArray());
const string SqlQuery = "select * from Table WHERE {0}";
var tableSearch = db.Query<Table>(string.Format(SqlQuery, joined));
Because everybody should know about string.Join()!!
And just for giggles:
const string SqlClause = "Searchstring LIKE '%{0}%'";
const string SqlQuery = "select * from Table WHERE {0}";
var tableSearch = db.Query<Table>(string.Format(SqlQuery, string.Join(" AND ", searchString.Split(' ').Select(word => string.Format(SqlClause, word.Replace("'", "''"))).ToArray())));
:)

Related

How to create an error or exception if the value entered is not in the database

I am creating a program where in I want to create an exception or an error if the user types a wrong value or inputs a value that does not exist in the database. I am using a gridview control in this matter.
Here I can show you a code snippet:
Dim searchString as String
searchString = txtSearchAnnouncement
SqlDataSource1.SelectCommand = "SELECT * FROM Announcements (WHERE announcement LIKE '%" + searchString + "%') OR (sender_name LIKE '%" + searchString + "%') OR (date_posted LIKE '%" + searchString + "%') OR (announcement_status LIKE '%" + searchString)
Any comments/suggestions are well accepted..
Just check if your query returns any valid values or not. If not, just display an appropriate message to the user.

How do you escape special characters in SQL Where clause?

How do you escape special characters in SQL Where clause? The SLASH (/) specifically. I can make it work with "LIKE" but I need the SQL to match the exact URL since "/path/to/file/" returns both rows:
URLs in database:
"/path/to/file/"
"/path/to/file/*/"
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE");
sb.append("WHERE URL LIKE '%" + url + "%'");
return getNamedParameterJdbcTemplate().query(sb.toString(), new MyTableMapper());
In SQL SLASH doesnt need to be scaped. You can use slashes in the query without problems.
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE");
sb.append("WHERE URL = '" + url + "'");
This query will work perfectly if url variable is something like "/path/to/file/"
Your problem isn't the slashes, if you only want to return an exact match, then don't use LIKE, use = -
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM MY_TABLE");
sb.append("WHERE URL = '" + url + "'");

SQL entries not showing in graph

For a school project I am trying to produce a graph that shows me all the entries between two dates from an SQL table. I am using the following code:
int bLost = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strstartDate = sdf.format(startDate.getDate());
String strendDate = sdf.format(endDate.getDate());
try {
conn = JavaConnect.ConnecrDb();
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
+ " WHERE Datecreated >= " + strstartDate
+ " AND Datecreated <=" + strendDate );
rsLost = pst.executeQuery();
if (rsLost.next()) {
bLost = rsLost.getInt(1);
}
} catch (Exception e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, "Table cannot be found");
}
// this is some stuff for the graph
DefaultCategoryDataset bagStats = new DefaultCategoryDataset();
// This should show me how many entries it found
bagStats.setValue(bLost, "Bagage Lost", "Bagage Lost");
The code works fine if i do the statement without the date part like this:
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
I also tried using BETWEEN statements and it didn't work either.
I'm all out of ideas, I would really appreciate any help!
Caspar
You need to put quotes around the string in your sql code, so it reads as follows:
pst = conn.prepareStatement("SELECT COUNT(*) FROM lost"
+ " WHERE Datecreated >= \'" + strstartDate
+ "\' AND Datecreated <=\'" + strendDate + "\'");
Whenever constructing sql statements, it is a good idea to print the string statement on the command line or in a message box while debugging, so you can see exactly what is being passed.
Also, if accepting user input into a variable, it is good practice to parameterize the query in order to avoid the possibility of sql injection attacks.

Unable to frame sql query correctly from java

I am trying to query data from my app, through postgresql DB. What I want to achieve is from "Users" where "Username"='stackoverflow'
If this query is written in the SQl editor and run, it gives the expected result.
Thus, am trying to send the query in the same format, as
String SQL_QUERY = "from " + "\"Users\"" + " where "
+ "Username" + "=" + "'"
+ request.getParameter("username") + "'";
When I run this, I get the following error:
unexpected char: '"' [from "Users" where Username=user1]
If I remove the double quotes, it wont work, saying table named users doesn't exist.
What is the way out of this deadlock? Where am I going wrong ??
Thank you.
This should be what you want:
String username = request.getParameter("username");
String SQL_QUERY = "SELECT * FROM \"Users\" WHERE \"Username\" ='" + username + "'";
You can check this by
System.out.println(SQL_QUERY);
which prints
SELECT * FROM "Users" WHERE "Username" ='foo'
ATTENTION/DANGER: This statement will solve your problem with the PostgreSQL mixed-case tablename and columnnames. BUT providing the value for Username to the query this way makes you vulnerable to even the easiest SQL-Injection attack. Please use PreparedStatement instead and write
String SQL_QUERY = "SELECT * FROM \"Users\" WHERE \"Username\" = ?";
Where's the SELECT clause of the query? It needs to be something like this:
String SQL_QUERY= "SELECT * FROM Users WHERE Username='" + request.getParameter("username") + "'";
Or like this:
String SQL_QUERY= "SELECT FirstName, LastName, Email FROM Users WHERE Username='" + request.getParameter("username") + "'";
Here's a very similar example that uses PreparedStatement to avoid a SQL injection security attack: https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Following the Postgresql syntax has in the end helped in getting a solution. Changed all the column names to small capitals and then tried, which solved most of the problems. Thanks to A.H
String SQL_QUERY = "FROM Users WHERE username ='" + username + "'";
Query query = objSession.createQuery(SQL_QUERY);
List list = query.list();
for (Iterator it = list.iterator(); it.hasNext();) {
Users objUsers = (Users) it.next();
System.out.println("Username: " + objUsers.userName);
System.out.println("Password: " + objUsers.password);
System.out.println("Name: " + objUsers.name);
}

help me with the following sql query

could somebody correct my following query, i am novice to software development realm,
i am to a string builder object in comma separated form to my query but it's not producing desired result qyery is as follows and
string cmd = "SELECT * FROM [placed_student] WHERE passout_year=#passout AND company_id=#companyId AND course_id=#courseId AND branch_id IN('" + sb + "')";
StringBuilder sb = new
StringBuilder();
foreach (ListItem li in branch.Items)
{
if (li.Selected == true)
{
sb.Append(Convert.ToInt32(li.Value)
+", ");
}
}
li is integer value of my check box list which are getting generated may be differne at different time ...please also suggest me some good source to learn sql..
Your problem lies here:
AND branch_id IN('" + sb + "')"
You'll end up with a query like:
... AND branch_id IN('1,2,3,')
If the branch_id column is an integer, you should not be quoting it, and you should insert the commas slightly differently to avoid a trailing one, such as with:
StringBuilder sb = new StringBuilder();
String sep = "";
foreach (ListItem li in branch.Items) {
if (li.Selected == true) {
sb.Append (sep + Convert.ToInt32(li.Value));
sep = ",";
}
}
String cmd = "SELECT * FROM [placed_student] " +
"WHERE passout_year = #passout " +
"AND company_id = #companyId " +
"AND course_id = #courseId " +
"AND branch_id IN (" + sb + ")";
This works by setting the initial separator to an empty string then to a comma after adding each item. So, when adding A, B and C, you'll get "A", "A,B" and "A,B,C'. I also removes the erroneous quoting on integers.
You'll also probably need to catch the case where none of your items are selected since otherwise you'll end up with:
... AND branch_id IN ()