I was wondering if anyone knew how to compile a text query for sql compact that goes like this :
command.CommandText = "SELECT * FROM tableName WHERE id = binary_Data"
The id column is a 32 byte binary column that is indexed and "binary_Data" is the binary data to compare to, but I am not sure how to get a "binary_Data" into the text query so sql can compare it.
The best way is to use parameters:
command.CommandText = "SELECT * FROM TableName WHERE id = #binary_data";
command.Parameters.AddWithValue("#binary_data", byteArray);
Alternatively, you could manually build a hex string prefixed with 0x to create a binary literal to append to the query but it's not recommended.
Related
I am building a query string like this.
string query = "SELECT * FROM " + table + " where DATE(Date) > " + howFarBack.ToString("yyyy-MM-dd");
Hwowever, when it executes
while (dataReader.Read())
I am seeing Dates well before the howFarBack ????
public List<OHLC> Select(string table, System.DateTime howFarBack)
{
string query = "SELECT * FROM " + table + " where DATE(Date) > " + howFarBack.ToString("yyyy-MM-dd");
//Create a list to store the result
var list = new List<OHLC>();
//Open connection
if (OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
var ohlc = new OHLC();
ohlc.Date = (System.DateTime)dataReader[0];
ohlc.Open = Math.Round((double)dataReader[1], 2);
When in doubt, try to debug by examining the resulting SQL query, not the C# code that formats the SQL query.
I would guess that your query lacks single-quote delimiters around the date literal. So it is ultimately a query like:
SELECT * FROM MyTable where DATE(Date) > 2021-11-02
But 2021-11-02 isn't a date, it's an arithmetic expression that evaluates to an integer: 2021 minus 11 minus 2 = 2008. This will certainly match a lot of dates you didn't intend it to.
You could solve this by ensuring that the right type of quotes are around your date literal (it's actually a string literal that is interpreted as a date when compared to a date).
SELECT * FROM MyTable where DATE(Date) > '2021-11-02'
But it's far better to use query parameters, as mentioned in the comment above.
SELECT * FROM MyTable where DATE(Date) > #howFarBack
Then you don't need quotes. In fact you must not use quotes around the parameter placeholder.
See Parameterized Query for MySQL with C# or many other references for using parameters in SQL statements in C#.
Also remember that parameters can only be used in place of a single literal value. You can't use parameters for table or column identifiers, or a list of values, or SQL keywords, etc.
I'm running the following query
cmd = new SqlCommand("SELECT * FROM addresses WHERE identifier NOT IN(#notIn)", _connector.getMsConnection());
When I view the value notIn and copy this query I get an empty result on my database (which I'm expecting). However when I'm running this code I get 6 results. The content of string notIN is for example
string notIn = "'201619011124027899693E8M2S3WOCKT9G6KHE11' ,'201619011124027899693E8M2S3WOCKT9G6KHE12'"
which combined with
SELECT *
FROM addresses
WHERE identifier NOT IN(#notIn)
Should create
SELECT *
FROM addresses
WHERE identifier NOT IN ('201619011124027899693E8M2S3WOCKT9G6KHE11',
'201619011124027899693E8M2S3WOCKT9G6KHE12' )
which runs as expected.
it should be like this:
cmd = new SqlCommand(string.Format("SELECT * FROM addresses WHERE identifier NOT IN({0})", notIn), _connector.getMsConnection());
This way the value of notIn will be concat to your string query.
Contrary to what the other answers say, concatenating the string to build the SQL is a bad idea, especially since the input values are strings. You open yourself up to SQL injection attacks.
You should be generating multiple parameters for each item in your list.
For example, if you have the input input:
var notIn = new[] { "A1", "B2", "C3" }
You'd want something like
for(var i = 0; i < notIn.Length; i++)
command.AddParamWithValue("p"+i, notIn);
And then you can build the SQL with concatenation (note that we are not concatenating an input here)
var sql = "SELECT * FROM addresses WHERE identifier NOT IN(" + string.Join(",", notIn.Select(i,v) => { "#p" + i; }) + ")";
Which then would look like:
SELECT * FROM addresses WHERE identifier NOT IN (#p0,#p1,#p2)
Alternatively, you could dump the values into a temporary table and do a join.
Note that the above is pseudocode, and may not compile verbatim, but should give you the right idea about how to procede.
It's because, you passed the #notIn as a whole string, which means, the SQL server see it as:
SELECT * FROM addresses WHERE identifier NOT IN('''201619011124027899693E8M2S3WOCKT9G6KHE11'',''201619011124027899693E8M2S3WOCKT9G6KHE12''')
So you got empty result
Try changing the "not in" to where clause and generate the where with C#:
string selectStatement = "SELECT * FROM addresses WHERE";
selectStatement += " identifier != '201619011124027899693E8M2S3WOCKT9G6KHE11' and identifier != '201619011124027899693E8M2S3WOCKT9G6KHE12'";
Or if you really want to use parameterized SQL, try doing it in stored procedure instead.
SQL Query
SELECT [ServerName]+ '\' + PARSENAME(REPLACE([Instance],'\','.'), 1) AS SIN,DATE FROM [DBReports].[dbo].[Accesslevelreport]
C# query
"SELECT [ServerName]+ '\' + PARSENAME(REPLACE([Instance],'\','.'), 1) AS SIN,DATE FROM [DBReports].[dbo].[Accesslevelreport]";
I want to convert it in C# but results are different as compared to running in SQL
Results from SQL= ANDSQLP47\DWMOD
Results from C#= ANDSQLP47ANDSQLP47\DWMOD
Expected Result
Data in [ServerName]= ANDSQLP47
Data in [Instance] =ANDSQLP47\DWMOD
SIN column will contain the Server Name and Instance Name, separated with a backslash ('\'). If the
instance field read from the database contains a slash in the text ('\'), remove
the slash and everything to the left of it before combining the fields for the
SIN column of the spreadsheet (only truncate this for processing - nothing
changes in the database).
For example : If the instance field contains
'ANDSQLP47\CTOPROD8R2', then truncate that to 'CTOPROD8R2' before
combining it with the ServerName field.
Just escape your query.
var query = #"SELECT [ServerName]\PARSENAME(REPLACE([Instance],'\','.'), 1) AS SIN,DATE" +
"FROM [DBReports].[dbo].[Accesslevelreport]";
or
var query = #"
SELECT [ServerName]\PARSENAME(REPLACE([Instance],'\','.'), 1) AS SIN, DATE
FROM [DBReports].[dbo].[Accesslevelreport]
";
Currently i am working on c# .net and i need to generate scripts ( sql insert scripts ) by using the data that is present in an excel sheet.
To be more specific,
If the excel sheet has three columns with
**column name** ColumName1, ColumName2, ColumName3
**data like** Value1, Value2, Value3
i need to write code to generate the insert script like -
INSERT [dbo].[TableName] ([ColumName1], [ColumName2], [ColumName3])
VALUES ('Value1', 'Value2', 'Value3')
Any ideas ?
You would need to write a forumla for the final column for instance:
="insert into tblyourtablename (intmine, strval) values ("&B4&", N'"&C4&"'); set #intpane = scope_identity(); INSERT INTO tblpane (nameid_fk,strtext,bitmine,vbarmine) VALUES (#intpane ,N'"&D8&"' ,0 ,convert(varbinary,''));"
This should get your started
EDIT
Why do some SQL strings have an 'N' prefix?
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT. See Article #2354 for a comparison of these data types.
For further reading please view the following link
http://databases.aspfaq.com/general/why-do-some-sql-strings-have-an-n-prefix.html
var myConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\Language_Batch1_OneClick.xls';Extended Properties=Excel 8.0;"); ;
var myCommand = new OleDbCommand();
var upCommand = new OleDbCommand();
int i = 0;
try
{
string sql = null;
string Value1 =null;
string Value2=null;
string Value3=null;
myConnection.Open();
myCommand.Connection = myConnection;
sql = "select ColumName1,ColumName1from,ColumName3 [sheet-name]";
myCommand.CommandText = sql;
var dataReader = myCommand.ExecuteReader();
{
value1=dataReader["ColumName1"].ToString();
value2=dataReader["ColumName2"].ToString();
value3=dataReader["ColumName3"].ToString();
string newQuery="INSERT [dbo].[TableName] ([ColumName1], [ColumName2], [ColumName3]) VALUES ('"+Value1+"', '"+Value2+"', '"+Value3+"')"
}
}
Read excel and get data ,then generate insert script
I have this program that is feeding me data. I take this data (string) and parse it so that the different fields can go into the respective db table column. I can parse the string but I can't find the right function or way to send them to the db. This is my second time working with sql server or database in general. I have done inserts this way
MyCommand.CommandType = System.Data.CommandType.Text;
MyCommand.CommandText = "INSERT INTO TimeStampTable(ID, TimeStamp) VALUES ('24', 'sep 13, 2009')";
From what I know, CommandType only allows either text or a stored procedure. In this case, I would want to insert the string that is being parsed.
string teststring = dtString;
string[] result = teststring.Split(',', ' ', ':', '=');
Console.WriteLine("The parsed string looks like this:");
foreach (string word in result)
{
Console.WriteLine(word);
}
This is my code that parses my incoming string. So I receive name address zip state, etc. I would like for name to go to col1, address to go to col2, etc. I think the ideal way to do this would be to convert my loop to something like this
foreach (string word in result)
{
SqlDatasource.InsertCommand=Insert into Tablename col1 col2 col3(word);
}
Does anyone have any suggestions?
I will answer your question directly, but there are many different ways that you could go about performing the same thing (I will list some at the end)
String insertQuery = "INSERT INTO TABLENAME (Col1, Col2, Col3...) VALUES (";
//This is also assuming that your data is in the same order as the columns
int isFirstLoop = true
foreach(string word in result)
{
if(!isFirstLoop)
insertQuery += ","
insertQuery += word;
isFirstLoop = false;
}
insertQuery += ")";
SqlDataSource.InsertCommand = insertQuery;
NOTE: this is very open to SQL Injection, so keep that in mind (do you trust your incoming source). There are ways to clean the data, but ultimately, I suggest some of the methods listed below
Alternatives:
Use a stored procedure over direct TSQL. Then you can map your data to SQLParameters, which (I believe) are built to scrub the data to protect against SQL Injection
Use a very basic ORM and/or LINQ so that you can work with objects directly. Then you only need to read the data into a POCO
I am sure there are other ways, however for some reason I am drawing a blank. I think that is because these are the most used alternatives :)