npgsql treats value as column name - npgsql

I am passing a value from a DataTable(it's source of course is a Postgres table) to a query and it's treating the value as a column name not a value. I know that it's because of the double quotes instead of single ones but what can I do to fix it?
A query fills a DataTable > I get the string from it's column "name" from it > I pass the string to this:
NpgsqlCommand id_test1 = new NpgsqlCommand("SELECT id_test FROM test WHERE name=" + test_name_string, conn);
but since it passes the name with " " insetad of ' ', I get an
ERROR: 42703: column "imaginaryname" does not exist

because name is a string and you did not wrap it with single quote.
To answer your question directly,
"SELECT id_test FROM test WHERE name='" + test_name_string + "'"
this is vulnerable with SQL Injection. Values must be parameterized.
NpgsqlCommand Class
Examples

Related

Updating ms access database [duplicate]

I am trying to create an SQL statement using user-supplied data. I use code similar to this in C#:
var sql = "INSERT INTO myTable (myField1, myField2) " +
"VALUES ('" + someVariable + "', '" + someTextBox.Text + "');";
var cmd = new SqlCommand(sql, myDbConnection);
cmd.ExecuteNonQuery();
and this in VB.NET:
Dim sql = "INSERT INTO myTable (myField1, myField2) " &
"VALUES ('" & someVariable & "', '" & someTextBox.Text & "');"
Dim cmd As New SqlCommand(sql, myDbConnection)
cmd.ExecuteNonQuery()
However,
this fails when the user input contains single quotes (e.g. O'Brien),
I cannot seem to get the format right when inserting DateTime values and
people keep telling me that I should not do this because of "SQL injection".
How do I do it "the right way"?
Use parameterized SQL.
Examples
(These examples are in C#, see below for the VB.NET version.)
Replace your string concatenations with #... placeholders and, afterwards, add the values to your SqlCommand. You can choose the name of the placeholders freely, just make sure that they start with the # sign. Your example would look like this:
var sql = "INSERT INTO myTable (myField1, myField2) " +
"VALUES (#someValue, #someOtherValue);";
using (var cmd = new SqlCommand(sql, myDbConnection))
{
cmd.Parameters.AddWithValue("#someValue", someVariable);
cmd.Parameters.AddWithValue("#someOtherValue", someTextBox.Text);
cmd.ExecuteNonQuery();
}
The same pattern is used for other kinds of SQL statements:
var sql = "UPDATE myTable SET myField1 = #newValue WHERE myField2 = #someValue;";
// see above, same as INSERT
or
var sql = "SELECT myField1, myField2 FROM myTable WHERE myField3 = #someValue;";
using (var cmd = new SqlCommand(sql, myDbConnection))
{
cmd.Parameters.AddWithValue("#someValue", someVariable);
using (var reader = cmd.ExecuteReader())
{
...
}
// Alternatively: object result = cmd.ExecuteScalar();
// if you are only interested in one value of one row.
}
A word of caution: AddWithValue is a good starting point and works fine in most cases. However, the value you pass in needs to exactly match the data type of the corresponding database field. Otherwise, you might end up in a situation where the conversion prevents your query from using an index. Note that some SQL Server data types, such as char/varchar (without preceding "n") or date do not have a corresponding .NET data type. In those cases, Add with the correct data type should be used instead.
Why should I do that?
It's more secure: It stops SQL injection. (Bobby Tables won't delete your student records.)
It's easier: No need to fiddle around with single and double quotes or to look up the correct string representation of date literals.
It's more stable: O'Brien won't crash your application just because he insists on keeping his strange name.
Other database access libraries
If you use an OleDbCommand instead of an SqlCommand (e.g., if you are using an MS Access database), use ? instead of #... as the placeholder in the SQL. In that case, the first parameter of AddWithValue is irrelevant; instead, you need to add the parameters in the correct order. The same is true for OdbcCommand.
Entity Framework also supports parameterized queries.
VB.NET Example Code
This is the example code for the wiki answer in vb.net, assuming Option Strict On and Option Infer On.
INSERT
Dim sql = "INSERT INTO myTable (myField1, myField2) " &
"VALUES (#someValue, #someOtherValue);"
Using cmd As New SqlCommand(sql, myDbConnection)
cmd.Parameters.AddWithValue("#someValue", someVariable)
cmd.Parameters.AddWithValue("#someOtherValue", someTextBox.Text)
cmd.ExecuteNonQuery()
End Using
UPDATE
Dim sql = "UPDATE myTable SET myField1 = #newValue WHERE myField2 = #someValue;"
' see above, same as INSERT
SELECT
Dim sql = "SELECT myField1, myField2 FROM myTable WHERE myField3 = #someValue;"
Using cmd As New SqlCommand(sql, myDbConnection)
cmd.Parameters.AddWithValue("#someValue", someVariable)
Using reader = cmd.ExecuteReader()
' ...
End Using
' Alternatively: Dim result = cmd.ExecuteScalar()
' if you are only interested in one value of one row.
End Using

The SQL statement works properly in SQL Server database, but errors in vb.net

I need to insert new record into a SQL Server database, but get
Incorrect syntax error
The strange thing is when I try to query the same statement in SQL Server itself, it works properly.
The code in vb.net is as follows:
insertSql = "INSERT INTO Seg_LINE VALUES (" & OBJECTID & ", 'test" + "', '" + "test" + "','" + DrainName + "'," & UID & ")"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
cmdInsert.ExecuteNonQuery()
The OBJECTID and UID are number parameters.
I cannot figure out what's wrong with my code, I am using vb.net(vs2102).
Most likely you have a DrainName value with a single quote in it. You're lucky the query is just failing, and not executing unwanted commands on your DB server. Don't use string concatenation like that to build queries! You need to use query parameters, like this:
insertSql = "INSERT INTO Seg_LINE VALUES (#ObjectID, 'test', 'test', #DrainName, #UID)"
logger.Info("insert sql = " + insertSql)
Dim cmdInsert As New SqlClient.SqlCommand(insertSql, Sqlconnection)
'I'm guessing at these parameter types. Use the actual db types of the columns
cmdInsert.Parameters.Add("#ObjectID", SqlDbType.Int).Value = OBJECTID
cmdInsert.Parameters.Add("#DrainName", SqlDbType.NChar, 50).Value = DrainName
cmdInsert.Parameters.Add("#UID", SqlDbType.Int).Value = UID
cmdInsert.ExecuteNonQuery()
Changing the code this way will also likely fix your syntax error.

Search Engine using TextBox, ComboBox and RadioButton

I am developing a search engine within WindowsForms,
I'm using VB.Net 2010 and SQL Server 2008,
My connection is ADO.Net
I experience difficulties in concatenating strings whenever I retrieve records from the database using a textbox, combobox and a radiobutton.
I would like to retrieve record based from the values of those objects,
Dim Condition1 As String = TextBox1.Text
Dim Condition2 As String = ComboBox1.Text
Dim Condition3 As String = RadioButton.Text
When I try to concatenate, I use the operator AND..
SELECT * FROM TableName WHERE (Condition1 AND Condition2 AND Conditon3)
It gives me an error when some objects doesnt have a value.
Incorrect syntax near the word AND.
NEVER concatenate strings to make queries! use SQL Parameters! The query you posted is prone to SQL Injection.
Dim query as String = "SELECT * FROM TableName WHERE Column1 = #Column1 AND
Column2 = #Column2 AND Column3 = #Column3"
Dim cmd As SqlCommand
cmd.Parameters.AddWithValue("#Column1", textBox1.Text)
cmd.Parameters.AddWithValue("#Column2", comboBox1.Text)
cmd.Parameters.AddWithValue("#Column3", radioButton1.Text)
Apart from the above, the conditions you are trying to concatenate are not valid. Anything that comes after the WHERE clause should specify the column name and the value like what I did above. So condition1 should be for example :
// If the column type is varchar then single quotes must be used
Dim Condition1 As String = String.Format("Name = '{0}'", TextBox1.Text)

Converting a resultset variable to an array

I am using SSIS (VS 2008) and I want to take a populated resultset variable (populated from an EXECUTE SQL task) and convert within an SSIS Script Component (c#) it into an array.
The resultset contains a single column.
What would be the code to do this?
Edit: This is for a backfilling exercise; in normal circumstances, a web app calls a proc on the db that passes in a text string and gets a list of matching words based on this kind of query:
SELECT [Term]
FROM [dbo].[ATableOFTerms] WITH ( NOLOCK )
WHERE CHARINDEX(' ' + Term + ' ', #StringBeingSearched) > 0
Once the web app gets this list, it has a lot of business rules around what it converts it to but essentially it takes the list of matching terms and generates a single string that is then used for passing into a fulltext search.
The backfilling process in SSIS needs to mimic that so the script component has the same web app code that deals with the business logic but I needed c# code that does the above. Which is fine, I am returning all the [ATableTerms] into a resultset variable but now I need populate an array from the variable.
When I have this I can use string.Contains to achieve the same result.
IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0This is how it was solved, although I'd love to get an alternative to this.
OleDbDataAdapter adapter = new OleDbDataAdapter();
string Title = " " + Row.Title + " ";
DataTable dt = new DataTable();
adapter.Fill(dt , Variables.ATableOfTerms);
ArrayList terms = new ArrayList();
ArrayList returnedTerms = new ArrayList();
foreach (DataRow dr in dt.Rows)
{
terms.Add(" " + dr["Term"] + " ");
}
foreach (string term in terms)
{
if (Title.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
{
returnedTerms.Add(term.Trim());
}
}

Search all dates before a specific date in a database (VB.NET|OLE)

I have a database (MDB, Access) and I connect it to my program using an OLE object,
now I have in the db a column filled with dates (ddmmyy),
I want to search and view (in Data grid view) all the fields that has a date before a Specific Date that I define .
the code of search that I used is :
SQLstr = "SELECT * FROM tb WHERE anomber = '" & TextBox1.Text & "'"
What do I have to do?. Thanks.
use the parameters to pass the date to the query, it's more saver(no sql injection) and more perfect(it will convert the date format to the correct format)
SQLstr = "SELECT * FROM tb WHERE anomber < ?"
Command.Parameters.Add(New OleDbParameter("#anomber", TextBox1.Text))
Command.CommandText = SQLstr
Edit:
if the anomber field is the date field so the user can use < instead of =.
the OP question not clear about what he wants.
Edit2:
after executing the command you should assign the results to the grid that you are using to display the data.

Resources