Parameterized update query is not working in c# - c#

I am trying to update details but the query is not working. client id is auto-generated.
here is my code
try
{
con.Open();
SqlCommand updatecmd = new SqlCommand();
updatecmd.CommandType = CommandType.Text;
// long client_id = CreateID();
updatecmd.CommandText= "UPDATE client_info SET companyname = #companyname, url = #url, industry = #industry, contactperson1 = #contactperson1, contactperson2 = #contactperson2, designation = #designation, fax = #fax, phone = #phone, mobile = #mobile, emailid1 = #emailid1, emailid2 = #emailid2, baddress = #baddress, bcity = #bcity, bstate = #bstate, bzipcode = #bzipcode, bcountry = #bcountry, regaddress = #regaddress, regcity = #regcity, regstate = #regstate, regzipcode = #regzipcode, regcountry = #regcountry WHERE client_id = #client_id";
// updatecmd.Parameters.AddWithValue("#client_id", client_id);
updatecmd.Parameters.AddWithValue("#companyname", txtcompanyname.Text);
updatecmd.Parameters.AddWithValue("#url", txturl.Text);
updatecmd.Parameters.AddWithValue("#industry", drpindustry.Text);
updatecmd.Parameters.AddWithValue("#contactperson1", txtcontactperson1.Text);
updatecmd.Parameters.AddWithValue("#contactperson2", txtcontactperson2.Text);
updatecmd.Parameters.AddWithValue("#designation", txtdesignation.Text);
updatecmd.Parameters.AddWithValue("#fax", txtfaxnumber.Text);
updatecmd.Parameters.AddWithValue("#phone", txtphone.Text);
updatecmd.Parameters.AddWithValue("#mobile", txtmobile.Text);
updatecmd.Parameters.AddWithValue("#emailid1", txtemailid1.Text);
updatecmd.Parameters.AddWithValue("#emailid2", txtemailid2.Text);
updatecmd.Parameters.AddWithValue("#baddress", txtbaddress.InnerText);
updatecmd.Parameters.AddWithValue("#bcity", txtbcity.Text);
updatecmd.Parameters.AddWithValue("#bstate", txtbstate.Text);
updatecmd.Parameters.AddWithValue("#bzipcode", txtbzipcode.Text);
updatecmd.Parameters.AddWithValue("#bcountry", bddlCountries.Text);
updatecmd.Parameters.AddWithValue("#regaddress",txtraddress.InnerText);
updatecmd.Parameters.AddWithValue("#regcity", txtrcity.Text);
updatecmd.Parameters.AddWithValue("#regstate", txtrstate.Text);
updatecmd.Parameters.AddWithValue("#regzipcode",txtrzipcode.Text);
updatecmd.Parameters.AddWithValue("#regcountry",
rddlCountries.Text);
updatecmd.ExecuteNonQuery();
Its not showing error and exception but data is not stored in DB.

Related

'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Additional information: Incorrect syntax near ','

When I am trying to update the SQL Server data to upper case from visual studio C# in asp.net I am getting this error:
'System.Data.SqlClient.SqlException' occurred in System.Data.dll but
was not handled in user code Additional information: Incorrect syntax
near ','
Code
String applicantSql = "SELECT applicantId, fullName, idNumber, idType, nationality, race, gender FROM applicant";
SqlCommand cmd = new SqlCommand(applicantSql, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
//fill the datatable with data
da.Fill(dt);
// Decrypt / Encrypt and Convert all Data to Uppercase
foreach (DataRow dr in dt.Rows)
{
string idNumber = dr["idNumber"].ToString();
string dcIdNumber = c.decryptInfo(idNumber).ToUpper();
oupdatedIdNumber = dr["idNumber"].ToString();
oupdatedFullName = dr["fullName"].ToString();
oupdatedIdType = dr["idType"].ToString();
oupdatedNationality = dr["nationality"].ToString();
oupdatedRace = dr["race"].ToString();
oupdatedGender = dr["gender"].ToString();
updatedIdNumber = c.encryptInfo(dcIdNumber);
updatedFullName = dr["fullName"].ToString().ToUpper();
updatedIdType = dr["idType"].ToString().ToUpper();
updatedNationality = dr["nationality"].ToString().ToUpper();
updatedRace = dr["race"].ToString().ToUpper();
updatedGender = dr["gender"].ToString().ToUpper();
// Update applicant Table with latest data
string updateApplicantSql = "UPDATE applicant SET idNumber = #idNumber, fullName = #fullName, idType = #idType, nationality = #nationality, race = #race, gender = #gender";
updateApplicantSql += " WHERE idNumber = #oidNumber AND fullName = #ofullName AND idType = #oidType AND nationality = #onationality, race = #orace, gender = #ogender";
SqlCommand cmdUpdateApplicant = new SqlCommand(updateApplicantSql, connection);
connection.Open();
cmdUpdateApplicant.Parameters.AddWithValue("#idNumber", updatedIdNumber);
cmdUpdateApplicant.Parameters.AddWithValue("#fullName", updatedFullName);
cmdUpdateApplicant.Parameters.AddWithValue("#idType", updatedIdType);
cmdUpdateApplicant.Parameters.AddWithValue("#nationality", updatedNationality);
cmdUpdateApplicant.Parameters.AddWithValue("#race", updatedRace);
cmdUpdateApplicant.Parameters.AddWithValue("#gender", updatedGender);
cmdUpdateApplicant.Parameters.AddWithValue("#oidNumber", oupdatedIdNumber);
cmdUpdateApplicant.Parameters.AddWithValue("#ofullName", oupdatedFullName);
cmdUpdateApplicant.Parameters.AddWithValue("#oidType", oupdatedIdType);
cmdUpdateApplicant.Parameters.AddWithValue("#onationality", oupdatedNationality);
cmdUpdateApplicant.Parameters.AddWithValue("#orace", oupdatedRace);
cmdUpdateApplicant.Parameters.AddWithValue("#ogender", oupdatedGender);
cmdUpdateApplicant.ExecuteNonQuery();
connection.Close();
}
Change this:
updateApplicantSql += " WHERE idNumber = #oidNumber AND fullName = #ofullName AND idType = #oidType AND nationality = #onationality, race = #orace, gender = #ogender";
to
updateApplicantSql += " WHERE idNumber = #oidNumber AND fullName = #ofullName AND idType = #oidType AND nationality = #onationality and race = #orace and gender = #ogender";
replace commas by and.

c# update/insert from datagridview

Whenever the code is executed, it always return that the ID value is not supplied that will cause an error. Would someone please show me where is my error? In some queries there is also sqlcommand.Parameters.Clear(); which is not included in this code.
The #ID should be pointing to the first column in the datagridview, where I can also set the match with the ID (primary key) in the table via SQL Management.
using (SqlCommand InsUpd = new SqlCommand(
#"IF EXISTS(SELECT 1 FROM dbo.Bokfuppg WHERE dbo.Bokfuppg.ID = #ID)
UPDATE dbo.bokfuppg
SET fnr = #Fnr, kto = #Kto, Ukto = #Ukto, avd = #Avd, prod = #Prod, proj = #Proj, ant = #Ant, bel = #Bel, Text = #Text, vbel = #Vbel, period = #Period
WHERE dbo.Bokfuppg.ID = #ID
ELSE
INSERT INTO dbo.bokfuppg(Fnr, Kto, Ukto, Avd, Prod, Proj, ant, bel, text, vbel, period) VALUES(#Fnr, #Kto, #Ukto, #Avd, #Prod, #Proj, #Ant, #Bel, #Text, #Vbel, #Period)", con))
{
con.Open();
using (SqlTransaction tr = con.BeginTransaction())
{
InsUpd.Transaction = tr;
InsUpd.Parameters.Add("#ID", SqlDbType.Int);
InsUpd.Parameters.Add("#Fnr", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Kto", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Ukto", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Avd", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Prod", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Proj", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Ant", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Bel", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Text", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Vbel", SqlDbType.NVarChar);
InsUpd.Parameters.Add("#Period", SqlDbType.NVarChar);
foreach (DataGridViewRow item in dataGridViewBokfuppg.Rows)
{
InsUpd.Parameters["#ID"].Value = item.Cells[0].Value;
InsUpd.Parameters["#Fnr"].Value = textBox1.Text;
InsUpd.Parameters["#Kto"].Value = item.Cells[1].Value;
InsUpd.Parameters["#Ukto"].Value = item.Cells[2].Value;
InsUpd.Parameters["#Avd"].Value = item.Cells[3].Value;
InsUpd.Parameters["#Prod"].Value = item.Cells[4].Value;
InsUpd.Parameters["#Proj"].Value = item.Cells[5].Value;
InsUpd.Parameters["#Ant"].Value = item.Cells[6].Value;
InsUpd.Parameters["#Bel"].Value = item.Cells[7].Value;
InsUpd.Parameters["#Text"].Value = item.Cells[8].Value;
InsUpd.Parameters["#Vbel"].Value = item.Cells[9].Value;
InsUpd.Parameters["#Period"].Value = item.Cells[10].Value;
InsUpd.ExecuteNonQuery();
}
tr.Commit();
}
}
MessageBox.Show("Record Updated Successfully");`

Send JSON through ActiveMQ

I'm trying to send a JSON format through ActiveMQ (C# Console Application), but right now I'm stock in the following:
If I send the direct JSON serialization (as string) the system adds backward slashes "\" to the text, which makes my listener unable to process the information.
I can remove the backward slashes by doing a JToken Parse, but I cannot send the var on ActiveMQ (ITextMessage requests a String, I'm sending a JToken) and of course if I do cast of the JToken to string I found again the backward slashes "\"
Any clue on how I can achieve my goal???
String IP = "172.29.75.43:61616";
String QueuesNameESF = "queue://MES2WMSTVOFFLINE";
try
{
Uri _uri = new Uri(String.Concat("activemq:tcp://" + IP));
IConnectionFactory factory = new ConnectionFactory(_uri);
using (IConnection conn = factory.CreateConnection())
{
using (ISession session = conn.CreateSession())
{
IDestination destination = SessionUtil.GetDestination(session, QueuesNameESF);
using (IMessageProducer producer = session.CreateProducer(destination))
{
SqlConnection dbConnection = new SqlConnection("Integrated Security=false;Data Source=smxsql08svr01;initial catalog=BSS;user id=sa;password=newshamu;Max Pool Size=75000");
SqlConnection internalConnection = new SqlConnection("Integrated Security=false;Data Source=smxsql08svr01;initial catalog=BSS;user id=sa;password=newshamu;Max Pool Size=75000");
String SearchPallet;
SqlCommand cmd = new SqlCommand();
dbConnection.Open();
SearchPallet = "";
SearchPallet = "Select Replace(Replace(Replace((Convert(varchar,GETDATE(),120) + Palletnum),'-',''),' ',''),':','') as 'ID', ";
SearchPallet += "'Y' as 'beFull','ZJ' as 'ext1','' as 'ext2','Y'as 'isCM',Part_Number as 'itemCode',linea as 'line',";
SearchPallet += "Case When len(Part_Number) = 12 then RIGHT(Part_Number,7) else RIGHT(Part_Number,8) end as 'lot',";
SearchPallet += "Palletnum as 'mainPallet',GETDATE() as 'sendTime','BSS' as'sender','8170' as'werks' From Finishgoods ";
//Remove if not test
SearchPallet += "Where PalletNum = #Palletnum GROUP by PalletNum,Part_Number,linea";
cmd.CommandText = SearchPallet;
cmd.Connection = dbConnection;
cmd.Parameters.Add("#Palletnum", SqlDbType.VarChar).Value = "PT01929734";//Pallet;//"PT01929734";
SqlDataReader rdr = cmd.ExecuteReader();
FirstLevel product = new FirstLevel();
if (rdr.Read())
{
//FirstLevel product = new FirstLevel();
product.guid = rdr.GetValue(0).ToString();
product.beFull = rdr.GetValue(1).ToString();
SecondLevel msg = new SecondLevel();
msg.carton = rdr.GetValue(8).ToString();
List<ThirdLevel> serials = new List<ThirdLevel>();
ThirdLevel sn = new ThirdLevel();
String SearchSN = "Select barcodenum as 'serNo',''as 'ext1',''as 'ext2' From Finishgoods where palletnum = #palletnum";
SqlCommand cmd_sn = new SqlCommand();
internalConnection.Open();
cmd_sn.Connection = internalConnection;
cmd_sn.CommandText = SearchSN;
cmd_sn.Parameters.Add("#Palletnum", SqlDbType.VarChar).Value = "PT01929734";
SqlDataReader rdr_sn = cmd_sn.ExecuteReader();
while (rdr_sn.Read())
{
sn.serNo = rdr_sn.GetValue(0).ToString();
sn.ext1 = rdr_sn.GetValue(1).ToString();
sn.ext2 = rdr_sn.GetValue(2).ToString();
serials.Add(sn);
}
rdr_sn.Close();
cmd_sn.Parameters.Clear();
cmd_sn.Dispose();
internalConnection.Close();
msg.serNoMsg = serials;
product.crtonMsg = msg;
product.ext1 = rdr.GetValue(2).ToString();
product.ext2 = rdr.GetValue(3).ToString();
product.isCM = rdr.GetValue(4).ToString();
product.itemCode = rdr.GetValue(5).ToString();
product.line = rdr.GetValue(6).ToString();
product.lot = rdr.GetValue(7).ToString();
product.mainPallet = rdr.GetValue(8).ToString();
product.sendTime = rdr.GetValue(9).ToString();
product.sender = rdr.GetValue(10).ToString();
product.werks = rdr.GetValue(11).ToString();
}
rdr.Close();
string json_ = JsonConvert.SerializeObject(product);
var json = JToken.Parse(json_);
conn.Start();
ITextMessage request = session.CreateTextMessage(json); //Here I need to send the JSON
producer.Send(request);
}
Console.WriteLine("send succeed");
Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Receive Failed");
Console.ReadLine();
}

Updating 2 rows in SQL database with one query string "UPDATE"

I need to figure out how to update the two rows in my database but cnt get my query string correct..
Here is the code that I am using. If you could provide me with a query string that would be great..
string birdnametextupdate = birdsnametext.Text;
string birdnamedetailsupdate = birdnamedetails.Text;
int row = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos Set PhotoName = #PhotoNewName Set Deatils = #DetailsNew WHERE PhotoID = #PhotoID";
SqlCommand myCommand = new SqlCommand(query, myConnection);
//create parameterised object
myCommand.Parameters.AddWithValue("#PhotoNewName", birdnametextupdate);
myCommand.Parameters.AddWithValue("#DetailsNew", birdnamedetailsupdate);
myCommand.Parameters.AddWithValue("#PhotoID", row);
myCommand.ExecuteNonQuery();
try this
string query = "UPDATE Photos Set PhotoName = '#PhotoNewName' ,Details = '#DetailsNew' WHERE PhotoID = '#PhotoID'";
I saw error in your query, do not duplicate set. just use comma instead
int photoId = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos SET PhotoName = #PhotoNewName, Details = #DetailsNew WHERE PhotoID = #PhotoID";
using(var cmd = new SqlCommand(query, myConnection))
{
cmd.Parameters.Add("#PhotoNewName").Value = birdsnametext.Text;
cmd.Parameters.Add("#DetailsNew").Value = birdnamedetails.Text;
cmd.Parameters.Add("#PhotoID").Value = photoId;
cmd.ExecuteNonQuery();
}
The Sql syntax is:
https://msdn.microsoft.com/en-us/library/ms177523.aspx
A simple example is:
UPDATE <tableName>
SET
<Column1> = <newColumn1Value>
,<Column2> = <newColumn2Value>
WHERE <condition>

ColdFusion query to C# Winform

I was given a query, originally done in ColdFusion, but I am having difficulties with the translation to a Winform use. I have a textbox that contains a concatenated string of other textboxes to make a case number. The purpose of this is to check for a record that might have been a transfer. In the first query, it is based on column caa443400048 either having something or being NULL. How would I incorporate that into a conditional statement for checking?
<cfquery name="q_transfer" datasource=#DSN#>
SELECT caa443400048
FROM caa44340
WHERE caa44340041 = '#SearchCaseNo#'
</cfquery>
<CFSET TransferCaseNo = "">
<CFSET TransferFlag = 'N'>
<CFIF #q_transfer.caa443400048# NEQ "">
<cfquery name="q_newcaseno" datasource=#DSN# >
SELECT caa44340041
FROM caa44340
WHERE caa443400018 = '#q_transfer.caa443400048#'
</cfquery>
<CFSET TransferFlag = 'Y'>
<CFSET TransferCaseNo = #SearchCaseNo#>
<CFSET SearchCaseNo = #q_newcaseno.caa44340041#>
</cfif>
Here is the C# code I am currently using:
string sql = "select COUNT (caa443400048) FROM caa44340 WHERE caa44340041 = ? ";
OdbcConnection con = new OdbcConnection("Dsn=XXXXX; User ID=XXXXX; Password=XXXXX");
con.Open();
OdbcCommand cmd = new OdbcCommand(sql, con);
cmd.Parameters.AddWithValue("caa44340041", txtCustomCaseNumber.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (count != 0)
{
MessageBox.Show("This is a transfer");
}
else
{
MessageBox.Show("This is not a transfer");
}
I'm not 100%, but maybe this may help:
var TransferFlag = "N";
var SearchCaseNo = "";
var q_transfer = "";
var q_newcaseno = "";
using (var con = new OdbcConnection("Dsn=XXXXX; User ID=XXXXX; Password=XXXXX"))
{
con.Open();
using (var cmd = new OdbcCommand("SELECT caa443400048 FROM caa44340 WHERE caa44340041 = ?", con))
{
cmd.Parameters.AddWithValue("#var", txtCustomCaseNumber.Text);
q_transfer = (string)cmd.ExecuteScalar();
}
if (!string.IsNullOrEmpty(q_transfer))
{
using (var cmd = new OdbcCommand("SELECT caa44340041 FROM caa44340 WHERE caa443400018 = ?", con))
{
cmd.Parameters.AddWithValue("#var", q_transfer);
q_newcaseno = (string)cmd.ExecuteScalar();
}
TransferFlag = "Y";
SearchCaseNo = q_newcaseno;
MessageBox.Show("This is a transfer");
}
else
MessageBox.Show("This is not a transfer");
}

Categories