How do you escape special characters in SQL Where clause? - sql

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 + "'");

Related

Can I concatenate a single quotation to a Swift String without the backslash

Trying to build up and bind an SQL query in swift.
var fieldnames = ""
var placeholders = ""
for key in keys {
// build up fieldnames
fieldnames = fieldnames + "'" + key + "'"
}
I end up with a string with backslashes in it like:
"INSERT INTO FormData (\'field\', \'field\', \'field\') VALUES ( Value, Value, Value)"
this causes the SQL statement to fail it doesn't like the backslashes.
Is there anyway to avoid them?

string must be exactly one character long issue

string SqlSelectQuery = " Select * From KTS Where STAFFNAME =" + Convert.ToChar(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
textBox2.Text = (dr["JOB TITLE"].ToString());
textBox3.Text = (dr["EXTN"].ToString());
textBox4.Text = (dr["Direct No."].ToString());
textBox5.Text = (dr["MOBILE (OFFICE)"].ToString());
textBox6.Text = (dr["SNO"].ToString());
i want to load data from sql server to visual studio by entering the name of the first name for the employee and he's job title mobile ext ....blla blla blla appear in the textboxes and my error is string must be exactly one character long
Convert.ToChar(textBox1.Text) requires a single character string, otherwise it throws a FormatException.
Your query should be
string SqlSelectQuery = " Select * From KTS Where STAFFNAME ='" + Convert.ToString(textBox1.Text)+"'";
You probably should use
Convert.ToString(textBox1.Text);
instead of
Convert.ToChar(textBox1.Text);
because you can't fit a String into a Char, and the textbox content will be most likely longer than one character
As per #RupeshPandey answer, you're also missing the quote to delimit the string in your query. your instruction should be
string SqlSelectQuery = "Select * From KTS Where STAFFNAME = '" +
Convert.ToString(textBox1.Text) +
"'";

I need a sql query to match two strings in where clause

'IP' is text field in both whiteList and BlackList tables(two different tables).'ip' is string storing ip address of current client.i want to check first if the ip address of client is in black list and then in whitelist(if not in blacklist).As it is string matching so '=' operator is not generating correct result.Also dont want to use 'like' because i am not searching for pattern rather exact match.
string[] ipPort = txtCIP.Text.Split(new char[] { ':' }, 2);
string ip = ipPort[0];
con.Open();
//MessageBox.Show("Connection Open ! ");
string query = "SELECT count(*) from BlackList WHERE IP=ip";
SqlCommand cmd = new SqlCommand(query, con);
int rowCount =1;
rowCount = (int)cmd.ExecuteScalar();
string wlq = "SELECT count(*) from WhiteList WHERE IP=ip";
SqlCommand cmd_wl = new SqlCommand(wlq, con);
int rowcount_wl;
rowcount_wl = (int)cmd_wl.ExecuteScalar();
if (rowCount > 1)
{
MessageBox.Show("This IP is black Listed.Please retry after a few seconds.");
}
else if (rowcount_wl > 0)
{
MessageBox.Show("This ip is present in white list.");
}
else
{ MessageBox.Show("IP is not present in whitelist"); }
con.Close();
I think issue is in your select,varialbe [ip] should be outside double quotes,
string query = "SELECT count(*) from BlackList WHERE IP=ip";
should be like this,
string query = "SELECT count(*) from BlackList WHERE IP=" + ip;
AND
string wlq = "SELECT count(*) from WhiteList WHERE IP=ip";
should be like this,
string wlq = "SELECT count(*) from WhiteList WHERE IP=" + ip;
string query = "SELECT count(*) from BlackList WHERE IP=" + ip;
string wlq = "SELECT count(*) from WhiteList WHERE IP=" + ip;
Your IP is stored in a variable, so use it as a variable. When you do WHERE IP=ip it's searching for the string = ip. So when you compare an IP 192.168.1.1 you are comparing against the word ip e.g.
if ("192.168.1.1" == "ip")
This will return false obviously.
String concatenation needs to be done to pass value of variable using plus operator
string query = "SELECT count(*) from BlackList WHERE IP="+ip;
without it the WHERE clause is searching for word ip rather than value contained in variable ip
Executing your query
string query = "SELECT count(*) from BlackList WHERE IP=ip";
will throw error invalid column name ip
will return all rows as you are matching column IP with itself i.e ip
To be searched as a string literal in WHERE clause , ip would need to be enclosed in single qoutes but ofcourse you don't want this.

sqlite-net query with parameter that contains multi instructions

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())));
:)

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 ()