How to convert C# string to varchar PostgreSQL? - c#

I have problem with types mismatch - I think. I have application which connects with database and sends query. That is how it works:
string wartosc1 = "'letters'";
NpgsqlCommand command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = "+wartosc1, conn);
but when I try to execute it, there is answer:
System.FormatException: Input string was not in correct format.
I suppose that there is problem with type of variable because when I just input:
SELECT * FROM RESOURCES WHERE TYPE ='letters'
Everything is ok.
Any ideas?

You need to use parameters to pass in the value to the query.
Read http://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx on how to do that.
var wartosc1 = "letters";
var command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = #type", conn);
command9.Parameters.Add("#type", wartosc1);

Because when you write;
"SELECT * FROM RESOURCES WHERE TYPE = " + wartosc1
Your command will be like;
SELECT * FROM RESOURCES WHERE TYPE = letters
which is wrong because I suppose your TYPE column is some text type. If you solve this an easy way, you can add your wartosc1 variable inside single quotes like;
"SELECT * FROM RESOURCES WHERE TYPE = '" + wartosc1 + "'"
But please don't use this way.
You should always use parameterized queries in your commands. It prevents, forget to use some quotes, commas etc.. But more important this kind of string concatenations are open for SQL Injection attacks.
string wartosc1 = "letters";
NpgsqlCommand command9 = new NpgsqlCommand("SELECT * FROM RESOURCES WHERE TYPE = #type", conn);
command9.Parameters.AddWithValue("#type", wartosc1);

Here is an example of string Interpolation using several variables and a date:
var dt = DateTime.Now.AddDays(-30);
string wartosc1 = "letters";
string myStatement = $#"
SELECT *
FROM RESOURCES res
WHERE res.DATE_EXAMPLE >= '{dt}'
AND res.TYPE = '{wartosc1}'
"
BEWARE This sql string IS open to sql injection, simply by setting
wartosc1 = "somevalue' AND someOtherStatement 'thenDoSomethingBeforeApostrophe";
However, it may be that your environment doesn't need to worry about that... the apostrophes aren't necessary around an int, but forget it around a datetime, and you'll throw errors.

Related

Replacing placeholders in prepared statement OleDbCommand.Parameters

I'm trying to perform a simple query on my MS Access DB from a Console Application through prepared statements.
The query tries to look for the desired value either in the "targa" field or in the "auto" field, to simplify the user interface with only one research label.
//grab field from GUI
string ricerca = Ricerca.Text;
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE '%?%'";
command = new OleDbCommand(queryTarga, con);
command.Parameters.Add("#p1", OleDbType.VarChar,ricerca.Length,"targa").Value = ricerca;
command.Parameters.Add("#p2", OleDbType.VarChar, ricerca.Length,"auto").Value = ricerca;
If I insert a known value for the first field "targa", the lookup works out with no issues.
If I insert anything for "auto", the lookup never returns any value!
The problem is that '%?%' gets interpreted in a weird way due to the single quotes and it's not recognising and setting the parameter correctly. By hardcoding the "ricerca" variable in the query string (without using '?') it works just fine:
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE '%" + ricerca + "%'";
Does anyone have a clue of how to set the parameter?
try this:
string queryTarga = "SELECT * FROM [Codici] WHERE targa = ? OR auto LIKE #p1";
command = new OleDbCommand(queryTarga, con);
command.Parameters.AddWithValue("#p1", "%" + Ricerca.Text + "%");

C# SQLite multiple keyword with like command

I used SQLite. The user will pull the days from checkbox and I'll show it in data grid view but the date is recorded as day and time so I have to use like instead of in command.
DataSet dataSet122;
listBox1.Items.Clear();
SQLiteConnection connection = new SQLiteConnection("Data Source =log.sqlite;Version=3;");
string search = checkBoxComboBox1.Text;
string[] array = search.Split(',');
for (int i = 0; i < array.Length; i++)
{
array[i] = "'" + array[i] + "'";
}
string names = String.Join(",", array);
listBox2.Items.Add(names);
string query = "SELECT * FROM Gemkay1 WHERE ZAMAN LIKE (" + names + ")";
command = new SQLiteCommand(query, connection);
connection.Open();
adapter = new SQLiteDataAdapter(command);
dataSet122 = new DataSet();
adapter.Fill(dataSet122, "Gemkay1");
dataGridViewSummary1.DataSource = dataSet122.Tables["Gemkay1"];
SQL syntax for all people where name ends with SMITH or WRIGHT:
WHERE name LIKE '%SMITH' OR name LIKE '%WRIGHT'
LIKE is not the same as IN - it accepts a single string argument on the right hand side. If you want multiple LIKEs you must repeat the LIKE clause separated by OR
IN can be used with multiple string but it does not accept wildcards:
WHERE name IN ('playwright', 'cartwright', 'shipwright')
If you try and put a wildcard in it will literally match that character.
-
As an aside, don't make SQL like you're doing there, with string concatenation of the values. Concatenate parameters in instead and give them values, for example:
var names = new []{"%wright", "%smith"};
var sql = new SqliteCommand("SELECT * FROM t WHERE 1=0 ");
for(int p = 0; p<names.Length; p++){
sql.CommandText += " OR name like #p" + p;
sql.Parameters.AddWithValue("#p"+p, names[p]);
}
This I what I mean when I say "concatenate parameters in, then give them a value".
If you ever work with sqlserver read this blog post
Use IN operator to select data where multiple values
"SELECT * FROM Gemkay1 WHERE ZAMAN IN ('2021-02-01','2021-02-02')";
to ignore time from date you can use date function:
"SELECT * FROM Gemkay1 WHERE date(ZAMAN) IN ('2021-02-01','2021-02-02')";
See SQLite date and time functions documentation for more info.

SQL Syntax in C#

I'm trying to understand why in C# if you have a sql string why you would have to put tick (') marks in the following where clause in order for this to work. Could someone please explain the reasoning behind this?
where ProgramServer='" + machineName.ToString() + "' and Active=1;
You can avoid those tick (') marks and use Parameters, They will also save you from SQL Injection.
The reason you see those ticks are because SQL expects string type values to be enclosed in single ticks.
What you're seeing is a dynamically built SQL query in the code. When querying based on a string value, the string must be wrapped in single quotes. The final SQL string would look something like:
select * from someTable where ProgramServer = 'YourMachineName' and Active = 1;
Unfortunately, that is far from the best way to do things. You should be using parameterized queries instead:
var query = "select * from someTable where ProgramServer = #machineName and Active = 1;";
using(var conn = new SqlConnection(connString))
{
var command = new SqlCommand(query, conn);
command.Parameters.Add("machineName", machineName.ToString());
// Execute and get the results
}

C# SQL string formatting

I am new to .net/C#. Coming from PHP and some Java, I am finding the new languages interesting and challenging.
I have an issue with a sql string
string query = #"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = '"+querystring + "' ORDER BY lname ASC";
Which to me, looks fine. however when run my solution and output the query as it is not working, I get this as my output:
select * from Users where role='member' and SUBSTRinG(lname, 1, 1)
= ' O ' ORDER BY lname ASC
This is output into my Firebug console (the page that uses this query is accessed via AJAX).
Is their a reason my 's are being turned into their code version, ie '&#39'
Thanks
In C# you should be using SqlCommand to excute the query, and to prevent sql injection using the parameter collection.
Your query seems fine - The issue might be the way you are running it or the parameters being supplied. Update your question with more details on what you are expecting vs what is happening, include any error messages generated.
Below is a general guideline of how to get data from a sql table to a c# Data Table object.
SqlConnection conn = new SqlConnection("YourConnectionString");
SqlCommand cmd = new SqlCommand(#"select * from Users where role='member' and
SUBSTRinG(lname, 1, 1) = #query ORDER BY lname ASC");
cmd.Parameters.AddWithValue("#query", querystring);
DataTable resultTable = new DataTable();
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(resultTable);
} finally {
if (conn.State != ConnectionState.Closed) conn.Close();
}
Console.WriteLine(String.Format("Matched {0} Rows.", resultTable.Rows.Count));
For SQL injection protection:
You can provide escape sequence for single quotes by replacing them with two single quotes '' so that it will be treated as a single quote inside SQL strings. Otherwise it is considered as a start or end of the string value in SQL.
Replacing single quotes using ' in .net is also preferred but its better going with two single quotes.

Data type mismatch in criteria expression | Access, OleDb, C#

I read/update data from MS Access using C#.
My code is:
public static void UpdateLastLogin(int userid, DateTime logintime) ///logintime = DateTime.Now
{
string sql = #"UPDATE [Customers] SET [LastLogin]=?";
OleDbParameter[] prms = new OleDbParameter[] {
new OleDbParameter("#LastLogin",logintime)
};
using (DAL dal = new DAL())
{
dal.UpdateRow(sql, false, prms);
}
}
When it comes to Dates, I having trouble.
This throws a "Data type mismatch in criteria expression." error.
(I removed WHERE clause for keeping it simpler)
Am I suuposed to enclose [LastLogin]=? question mark with single quotes, # signs .. does not help.
Any leads on how to handle DateTime objects with Access and OleDb provider will be greatly appreciated.
Thanks in advance.
There is a known issue with OleDb and dates. Try doing something like:
OleDbParameter p = parameter as OleDbParameter;
if (null == p)
parameter.DbType = DbType.DateTime;
else
p.OleDbType = OleDbType.Date;
Or use explicit format string:
value.ToString("yyyy-MM-dd hh:mm:ss")
I solved this using the following code
OleDbCommand cmd = new OleDbCommand(qry, cnn);
cmd.Parameters.Add("datenow", OleDbType.Date);
cmd.Parameters["datenow"].Value = DateTime.Now;
Firstly, no your SQL statement should be:
"UPDATE Customers SET LastLogin=#LastLogin"
Secondly, the reason you are receiving the date mismatch error will probably be your passing '?' as your date time into the LastLogin field instead of the actual logintime parameter.
maybe try
DateTime.Now.ToShortDateString() + ' ' + DateTime.Now.ToShortTimeString()
instead, pass it as String (and maybe enclose with # then)
Should it not be
"UPDATE Customers SET LastLogin='#LastLogin'"
And #LastLogin should be
logintime.ToString("yyyy-MM-dd hh:mm:ss")
edit
Could you not just inline the whole thing?
"UPDATE Customers SET LastLogin='" + logintime.ToString("yyyy-MM-dd hh:mm:ss") + "'"
Try setting the "DBTYPE" property of the parameter to identify it as a date, datetime or datetime2 as appropriate...
prms[0].DbType = DbType.DateTime;
There are 7 signatures to the new OleDbParameter() call, so you may change the signature instance, or just do explicitly as I sampled above since you only had 1 parameter in this case.

Categories

Resources