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

'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.

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?

Making SQL password query case sensitive using COLLATE

I am using the following SQL code in my VB in VS2013. I want to create a login form using a database of users stored into a UserList. However The query is not case sensitive. How do I change my query string to use COLLATE or any other case sensitive comparison
Dim Check As String = _
"SELECT COUNT(*) AS Expr1 FROM UserList HAVING (Username = '" & _
_UsernameTextBox.Text & "') AND ([Password]= '" & _PasswordTextBox.Text & _
"') AND (UserType = '" & User.ToString & "')"
With search
.CommandText = Check
.Connection = cn
If .ExecuteScalar() = 1 Then
Me.Hide()
If User = "Trader" Then
Trader.Show()
ElseIf User = "Broker" Then
Broker.Show()
ElseIf User = "Corporate" Then
Corporate.Show()
ElseIf User = "System" Then
SystemManager.Show()
End If
Else : MsgBox("IncorrectInput")
End If`
"SELECT COUNT(*) AS Expr1 FROM UserList
HAVING (Username = #username)
AND ([Password] COLLATE Latin1_General_CS_AS = #password)
AND (UserType = #usertype)
"
Apart from the fact that you don't have your password stored and compared with a slow salted cryptographic hash function (=non-reversible encryption), your query is also vulnerable to SQL-injection (when I use a username like "Jean le Rond d'Alambert" or just "d'Alambert".
Another bug is that when you save the password as plain text, say e.g. (n)varchar(32), I can enter a password that is longer than that (e.g. a sentence) ==> bug
Given you're writing a financial application ("broker", "corporate"), SQL-injection is an intolerable security risk.
You can for example MD5-hash your password (cheap & dirty):
master.dbo.fn_varbintohexstr(HashBytes('MD5', 'test'))
You have a "System.Data.SqlClient.SqlCommand",
there you can add a System.Data.SqlClient.SqlCommand
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
//
// Description of SQL command:
// 1. It selects all cells from rows matching the name.
// 2. It uses LIKE operator because Name is a Text field.
// 3. #Name must be added as a new SqlParameter.
//
using (SqlCommand command = new SqlCommand(
"SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
weight,
name,
breed);
}
}
}
If you do it right from the start, then you don't have to change anything later.

SQLite SELECT from VB.Net application (Win32)

I am trying to get a result from SQL database and keep it as a variable. But with my code (see below) it returns 0 (zero). Any ideas of what am i doing wrong?
Thanks
Function getName(name As String)
Dim SQLconnect As New SQLite.SQLiteConnection()
Dim SQLcommand As SQLite.SQLiteCommand
SQLconnect.ConnectionString = "Data Source=C:\tools\names.sqlite;"
SQLconnect.Open()
SQLcommand = SQLconnect.CreateCommand
SQLcommand.CommandText = "SELECT * FROM names WHERE name = " & name & " LIMIT 1;"
Dim sqlResponse As String = SQLcommand.ExecuteNonQuery()
End Function
EDIT: I am using "return sqlResponse" for return
First thing, the sql should be(I think):
SQLcommand.CommandText = "SELECT * FROM names WHERE name = '" & name & "' LIMIT 1;"
I am not sure how text is represented in SQLite but you need some kind of delimiter like a single quote in SQL Server.
Second thing, use paramterized query to stop yourself from being hijacked by SQL Injections
Third, a SELECT uses a ExecuteReader, and in case where you want only one item, try ExecuteScalar. ExecuteNonQuery is for insert, update delete.
ExecuteNonQuery does not return a value so therefore it will always be 0. You need to use
Dim sqlResponse As String = SQLcommand.ExecuteScalar()

pass null parameter to SQL server query

How can I pass a null parameter to a SQL server query.
I have a simple table with a nullable int column.
If I pass a .NET null value, I get a sql error. If I pass DBNull.Value, no row matches the filter. Is there a simple way to do this without using ISNULL.
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = ...;
connection.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;
cmd.CommandText = "select * from myTable where myColumn = ?";
OleDbParameter parameter = cmd.Parameters.Add(null, OleDbType.Integer);
parameter.DbType = System.Data.DbType.Int32 ;
parameter.IsNullable = true;
parameter.Value = DBNull.Value; // no row returned
parameter.Value = null; // sql error
var reader = cmd.ExecuteReader();
...
Since NULL does not match anything (even NULL = NULL is false), you have no choice other than using the IS NULL statement.
As ocdecio mention, NULL is not equal to itself. But you do have another option. If you are worried about NULL in this scenario, you can just put an empty string in your parameter value and write the query itself like this:
select * from myTable where COALESCE(myColumn,'') = ?
In SQL, null acts a bit differently to other values - you can't just evaluate things as being = null, as this doesn't really work, you need to use "myColumn is null" instead.
In your case, when you need to match either a value or a null, you might need to use a case statement in your where clause.
A bit of reading: wikipedia

Using an 'IN' operator with a SQL Command Object and C# 2.0

I would like to call a sql statement such as:
Select * From Table Where Column in ('value1', 'value2', 'value3')
Is it as simple as setting a command parameter's value equal to "('value1', 'value2', 'value3')"?
#Charles: You're going into the right direction, but we're using parametrized queries to mainly prevent SQL injections. Putting 'external' values (params string[] args) hardcoded in queries is asking for trouble. You can iterate the arguments, but you still have to use parameters like this:
string[] values = new [] {"value1", "value2", "value3", "value4"};
StringBuilder query = new StringBuilder("Select * From Table Where Column in (");
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection("Your connection string");
for(int i = 0; i < columns.Length; i++)
{
string arg = string.Format("#arg{0}", i);
cmd.Parameters.AddwithValue(arg, SanatizeSqlString(columns[i]));
sb.AppendFormat("{0}, ", arg);
}
sb = sb.Remove(sb.Length -2, 2);
sb.Append(")");
cmd.CommandText = sb.ToString();
This way you'll end up with a query like:
select * from table where column in (#arg0, #arg1, #arg2, #arg3)
Another option is to set the SqlCommand's commandtype to "text" and construct the entire Sql string in code... Assuming Column is a varchar, and you have the Values in a string arrray, named "paramValues"
StringBuilder sbSql = new StringBuilder
("Select * From Table Where Column in (");
string[] paramValues = new string[] {"value1", "value2", "value3"};
foreach (string val in paramValues)
sbSql.Append("'" + val + "', ");
sbSql = sbSql.Remove(sbSql.Length - 2, 2);
sbSql.Append(")");
SqlCommand cmd = new SqlCommand(sbSql.ToString());
cmd.CommandType = CommandType.Text;
if you only have three parameters for the in clause then yes you can use the parameters. Otherwise you can build dynamic SQL (Be careful of SQL injection attacks).
Another approach is to create a UDF which takes a delimited string and returns a table. then you could modify your query to be:
select * from
table inner join
dbo.fn_stringToTable(#params)