syntax error missing operator in date and time query expression - c#

cmd.CommandText = "SELECT * FROM " + TableName + " WHERE"
+ " [TIME_STAMP]=#" + TimeStamp.ToString("dd-MM-yyyy HH:mm") + "#"
+ " AND [Slave_Id]='" + SlaveUnitID
+ " AND [Parameter]='" + Param
+ "' AND [Status]='" + Status
+ "' AND [Reading]='" + Reading + "'";
dr = cmd.ExecuteReader();
I am getting error in the above query.Tried but getting the same, Plz help it out

Try to use parameterized query
conn.Open();
string query = "SELECT * FROM " + TableName + " WHERE [TIME_STAMP] =#date "
+" AND [Slave_Id]=#sid AND [Parameter] =#param "
+" AND [Status] =#status AND [Reading] = #reading"
qlCommand cmd = new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("#date", TimeStamp);
cmd.Parameters.AddWithValue("#sid", SlaveUnitID);
cmd.Parameters.AddWithValue("#param", Param);
cmd.Parameters.AddWithValue("#status", Status);
cmd.Parameters.AddWithValue("#reading", Reading );
dr = cmd.ExecuteReader();

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'

Im trying to insert this test data in my sql database and I'm getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'
Any ideas how to solve this?
DateTime date = DateTime.Now;
string test = "{'payload': {'businessName': 'COMPANY1', 'subscriberName': 'JOHN DOE', 'accountNumber': 'CY68005000121234567890123456', 'numberOfRecords': 1," +
"'currentBalance': 4195.5, 'transactions': [{'transactionNumber': 'TR00000000','sequenceNumber': '000','transactionCode': '305','actualDateTime': '201812041624'," +
"'transactionValueDate': '2018-12-04', 'transactionCurrencyCode': 'EUR', 'transactionAmount': -1149.5, 'balance': 4195.5, 'chequeNo': '', 'depositedBy': 'CY68005000121234567890123456'," +
"'customerReference': 'uniqueValue', 'paymentNotes': 'NOTES', 'exchangeRate': 0}]}, 'errors': null}";
trans = JsonConvert.DeserializeObject<HB_transactions>(test);
for (int i=0; i<trans.payload.transactions.Count; i++)
{
string query = "SELECT TransactionId FROM AABankTransTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dataReader = cmd.ExecuteReader();
bool exists = false;
while(dataReader.Read())
{
if(dataReader[0].ToString() == trans.payload.transactions[i].transactionNumber)
{
exists = true;
break;
}
}
dataReader.Close();
if (exists) continue;
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES ('" + trans.payload.transactions[i].transactionNumber + "', 'HB', " + args[0] + ", '" + trans.payload.transactions[i].transactionCurrencyCode + "', " +
trans.payload.transactions[i].transactionAmount + ", " + date + ", 0, '" + trans.payload.transactions[i].depositedBy + "', '" +
trans.payload.transactions[i].paymentNotes + "', " + DateTime.Parse(trans.payload.transactions[i].transactionValueDate) + ")";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
Solved by using SQL parameters instead of string concatenation.
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES (#TransID, 'HB', #COMID, #curr, #amount, #dlDate, 0, #depositor, #Details, #TransDate)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#TransID", trans.payload.transactions[i].transactionNumber);
cmd.Parameters.AddWithValue("#COMID", args[0]);
cmd.Parameters.AddWithValue("#curr", trans.payload.transactions[i].transactionCurrencyCode);
cmd.Parameters.AddWithValue("#amount", trans.payload.transactions[i].transactionAmount);
cmd.Parameters.AddWithValue("#dlDate", date);
cmd.Parameters.AddWithValue("#depositor", trans.payload.transactions[i].depositedBy);
cmd.Parameters.AddWithValue("#Details", trans.payload.transactions[i].paymentNotes);
cmd.Parameters.AddWithValue("#TransDate", DateTime.Parse(trans.payload.transactions[i].transactionValueDate));
cmd.ExecuteNonQuery();

Looping parameterized query

I've been looking for its solution for some time now, I've seen similar questions here on SO but the answers there didn't solve my problem. In my situation, I would like to loop through the rows of datagridview values to insert it to MySql database. The number of rows in the datagridview will depend on the user. When I try to input 2 or more rows of datagridview values and try to insert it to the database, only the first row of data is inserted successfully.
Here is my code:
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
The error: Parameter '#num_Delivery' has already been defined. I'm new at using C# language. Any ideas and suggestions would be welcomed.
You can do it like this. It should work.
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
cmd.Parameter.Clear();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
Move
MySqlCommand cmd = new MySqlCommand();
in the for loop:
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
or clear its Parameters collection:
string sql = "INSERT INTO delivery(DeliveryNumber, CreationDate, Client, Product, Price, Quantity, Total) " +
"VALUES(#num_Delivery, " + "#dgv_datevalue" + ", " +
"#name_Client" + ", " +
"#name_Product" + ", " +
"#priceof_Produt" + ", " +
"#quan_Product" + ", " +
"#price_Total" + ");";
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = SecurityMod.dbconn();
for (int i = 0; i < dgv_ctrl.Rows.Count; i++)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#num_Delivery", num_Delivery);
cmd.Parameters.AddWithValue("#dgv_datevalue", DateTime.Parse(dgv_ctrl.Rows[i].Cells["Creation_Date"].Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
cmd.Parameters.AddWithValue("#name_Client", dgv_ctrl.Rows[i].Cells["Client_name"].Value);
cmd.Parameters.AddWithValue("#name_Product", dgv_ctrl.Rows[i].Cells["Product_name"].Value);
cmd.Parameters.AddWithValue("#priceof_Produt", dgv_ctrl.Rows[i].Cells["Price_ofProduct"].Value);
cmd.Parameters.AddWithValue("#quan_Product", dgv_ctrl.Rows[i].Cells["Quantity_ofProduct"].Value);
cmd.Parameters.AddWithValue("#price_Total", dgv_ctrl.Rows[i].Cells["Total_Price"].Value);
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
Sql string can be out of loop.

Foreach Loop is not Working properly

There is problem in this code when I use parameterized query loop get one file name in string filename = Path.GetFileName(item); variable again and again
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + newtable));
int a = 0;
OleDbCommand cmd = new OleDbCommand();
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb";
cmd = mycon.CreateCommand();
mycon.Open();
DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = "00" + a.ToString();
// Response.Write("Number (" + a.ToString() + ") " + filename + " " + ips + " " + t1 + " " + v + " " + some + " " + some + "<br/><br/>");
// cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.AddWithValue("#p1", filename);
cmd.Parameters.AddWithValue("#p2", ips);
cmd.Parameters.AddWithValue("#p3", dateTime.ToString("dd/MM/yyyy"));
cmd.Parameters.AddWithValue("#p4", newtable);
cmd.Parameters.AddWithValue("#p5", TextBox4.Text);
cmd.Parameters.AddWithValue("#p6", TextBox3.Text);
cmd.ExecuteNonQuery();
}
But when I use normal insert query
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES('" + filename + "','" + ips + "','" + dateTime.ToString("dd/MM/yyyy") + "','" + newtable + "','" + TextBox4.Text + "','" + TextBox3.Text + "')";
loop is working alright and get all the name of files at specific location. Please let me know why ?Is there any problem in my logic ?
cmd.Parameters collection is not cleared between iterations. You should create parameters before the loop and set values in the loop, instead of using AddWithValue
cmd = mycon.CreateCommand();
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES (?,?,?,?,?,?)";
cmd.Parameters.Add('#p1',...);
...same for other params...
mycon.Open();
DateTime dateTime = DateTime.UtcNow.Date;
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = "00" + a.ToString();
cmd.Parameters["#p1"].Value = filename;
...same for other params...
cmd.ExecuteNonQuery();
}
However you can just add cmd.Parameters.Clear() after cmd.ExecuteNonQuery() :)
As it noted in MSDN
OleDbParameterCollection.AddWithValue Method
Adds a value to the end of the OleDbParameterCollection
So engine doesn't see #p1 added on the second iteration because it already found #p1 added on the first one.

SQL c# updating table

I am doing this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where JobID=" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
JobID is a uniqueidentifier
And I am getting this error:
Conversion failed when converting from a character string to uniqueidentifier.
What am I doing wrong?
The JobID field looks like this:
DB9424E5-1E73-4108-A855-B252E516A2A2
2EB17B8B-C0A1-46FE-82AF-37AEF2A8A6EC
C24F0460-7667-4A3A-8D8F-64B9728C2359
8DCDB020-8C7B-493E-9D21-719CBAFC16B6
This will be more secure (safe from SQL-injection), easer to read and understand, and faster because prepared statements get their execution plan cached. If you have different sql, it can't use a cached execution plan.
SqlCommand cmd =
new SqlCommand(
#"update FileLog set FaxStatus=#fs, FaxedPageCount=#ct, #dtFaxed=#dt, ......., where JobID=#id")
{CommandType = CommandType.Text};
cmd.Prepare();
cmd.Connection = connection;
cmd.Parameters["#id"].Value = row.ItemArray[0];
...
i found the solution. turns out you need to do this:
var command = new SqlCommand(query, myConnection);
foreach (DataRow row in dt.Rows)
{
query = #"update FileLog set
FaxStatus=" + "'" + row.ItemArray[0].ToString() + "'," +
"FaxedPageCount=" + "'" + row.ItemArray[1].ToString() + "'," +
"dtFaxed=" + "'" + row.ItemArray[2].ToString() + "'," +
"BiscomCode=" + "'" + row.ItemArray[5].ToString() + "', " +
"RetryCount=" + "'" + row.ItemArray[4].ToString() + "' " +
"where CONVERT(VARCHAR(255), JobID) =" + "'" + row.ItemArray[3].ToString() + "'";
command = new SqlCommand(query, myConnection);
command.ExecuteNonQuery();
}
you have to convert it to a varchar first
It's very likely one of your job ids is not a valid Guid.
Here's a method to check for guid:
public static bool IsGuid(string input)
{
Regex isGuid = new Regex(#"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
try
{
return isGuid.IsMatch(input);
}
catch
{
return false;
}
}
So before issuing the query command do a check on the jobid. If it doesn't match, escape it and log it to revisit later.

C# Insert and Update content to DataGridView do not work !

I got a really troublesome issue here, the query seems to be apparently corrent but it returns no rows of data...
Basically the issue is after an insert, I make a select to obtain the auto increment number (NAlbum) to a variable (I'm using C#), here's the piece of code that's troubling me
//Associar ID de Artista
ClassBD.DBMyReader(
"SELECT NArtista " +
"FROM Artistas " +
"WHERE (Nome = '" + CBBoxAddArtista.Text + "')");
ClassBD.myReader.Read();
temptabelas[0] = ClassBD.myReader.GetInt32(0);
//Associar ID da Editora
ClassBD.DBMyReader(
"SELECT NEditora " +
"FROM Editora " +
"WHERE (Nome = '" + CBBoxAddEditora.Text + "')");
ClassBD.myReader.Read();
temptabelas[1] = ClassBD.myReader.GetInt32(0);
//Associar ID da Media
ClassBD.DBMyReader(
"SELECT NMedia " +
"FROM Media " +
"WHERE (Nome = '" + CBBoxAddMedia.Text + "')");
ClassBD.myReader.Read();
temptabelas[2] = ClassBD.myReader.GetInt32(0);
//Associar ID do Genero
ClassBD.DBMyReader(
"SELECT NGenero " +
"FROM Genero_de_Musica " +
"WHERE (Nome = '" + CBBoxAddGenero.Text + "')");
ClassBD.myReader.Read();
temptabelas[3] = ClassBD.myReader.GetInt32(0);
ClassBD.DBMyInsertCommand("INSERT INTO Albuns " +
"(NArtista, NEditora, NGeneroDeMusica, NMedia, Nome, [Ano de Edição])" +
"VALUES (" + temptabelas[0] + "," + temptabelas[1] + "," + temptabelas[2] + "," + temptabelas[3] + ",'" + TxtAddMusicaAlbum.Text + "'," + int.Parse(TxtAddAnoEdicao.Text) + ")");
ClassBD.DBMyReader("SELECT MAX(NAlbum) AS Actual " +
"FROM Albuns");
tempnalbum = ClassBD.myReader.GetInt32(0);
musicasBindingSource.Filter = "NAlbum = " + tempnalbum;
Thanks in advance,
Luis Da Costa
1st. You Need to parametized your query for cleaner syntax.
Example:
string CommandText = "select NArista from Artista where Nome=#Nome";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Nome",CBBoxAddArtista.Text);
rdr = cmd.ExecuteReader();
while(rdr.Read())
{
temptabelas[0] = rdr["NAtista"].ToString()
}
After Getting the Result loaded to Data gridview then loop all the values
Then use your insert statement.
Example:
foreach (DataGridViewRow dr in Datagridview1.Rows)
{
//Do your Code
"INSERT INTO Albuns " +
"(NArtista, NEditora, NGeneroDeMusica, NMedia, Nome, [Ano de Edição])" +
"VALUES (#1,#2,#3,#4,#5,#6)";
// Add parameter
cmd.Parameters.AddWithValue("#1",(string) dr.Cells["Natista"].Value.ToString());
.
.
.
.
cmd.Parameters.AddWithValue("#6",int.Parse(TxtAddAnoEdicao.Text)
cmd.ExecuteNonQuery();
}
HI Everyone,
ClassBD.DBMyInsertCommand("INSERT INTO Albuns " +
"(NArtista, NEditora, NGeneroDeMusica, NMedia, Nome, [Ano de Edição]) " +
"VALUES (" + temptabelas[0] + "," + temptabelas[1] + "," + temptabelas[2] + "," + temptabelas[3] + ",'" + TxtAddMusicaAlbum.Text + "'," + int.Parse(TxtAddAnoEdicao.Text) + ")");
OleDbConnection connection = new OleDbConnection(ClassBD.MyConnectionString);
connection.Open();
OleDbCommand MyCommand = new OleDbCommand("SELECT NAlbum FROM Albuns WHERE (Nome = #Nome)", connection);
MyCommand.Parameters.AddWithValue("#Nome", TxtAddMusicaAlbum.Text);
OleDbDataReader myReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
ClassBD.tempnalbum = myReader.GetInt32 ;
"Hi, I've asked this very question yesterday, you told me to parameterize the query, and so I did... However, it still comes up with no rows... Help?"
"(The Insert is correct, I've checked it's entry)
Private Sub BoundLoadButton_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles BoundLoadButton.Click
swatch.Reset()
swatch.Start()
Cursor = Cursors.WaitCursor
Try
Using BoundObject As New UnboundClass(mMySQLConnectionString)
Call BoundObject.BoundDataLoading(UnboundDataGridView, _
RecordCountTextBox, _
mErrorMsgString)
If Not IsNothing(mErrorMsgString) Then
Cursor = Cursors.Default
MessageBox.Show(mErrorMsgString, _
Me.Text, _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
End Using
Catch exError As Exception
MessageBox.Show(exError.Message, _
Me.Text, _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Try
Cursor = Cursors.Default
swatch.Stop()
mTimeDouble = swatch.ElapsedMilliseconds * 0.001
BoundTimeTextBox.Text = mTimeDouble.ToString
End Sub

Categories

Resources