Syntax error near: When connecting to mysql database - c#

I've read on a lot of threads, but none of them is actually working, thats why I'm asking a new question.
Well, so I'm trying to insert values into my MySQL database but I'm getting the error.
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'Desc, Detectors, DetectorNos,
Question1, Question2, SpecialPrec, OfficerSign, Of' at line 1'
And I can't find where the problem is. I've been trying for hours without any result, even read all throught a hundred of times but still no luck. So I need someone else to take a look.
public string detector = "";
public string questions = "";
public string question2 = "";
public string capOrCheif = "";
private void btn_send_Click(object sender, EventArgs e)
{
if(cbox_detectors_yes.Checked == true)
{
detector = "Yes";
}
if(cbox_yes1.Checked == true && cbox_yes3.Checked == true && cbox_yes4.Checked == true && cbox_yes5.Checked == true && cbox_yes6.Checked == true && cbox_yes7.Checked == true)
{
questions = "Yes";
}
if(cbox_yes2.Checked == true)
{
question2 = "Yes";
}
if(cbox_cheif.Checked == true)
{
capOrCheif = "Cheif Engineer";
}
else if(cbox_captain.Checked == true)
{
capOrCheif = "Captain";
}
else if(cbox_na2.Checked == true)
{
question2 = "N/A";
}
else if(cbox_detectors_na.Checked == true)
{
detector = "N/A";
}
string constring = "Server = **; Database = **; User Id = **; Password = ***; Sslmode = none;";
string Query = "INSERT INTO tbl_permit (Username, Ship, Date, TimeFrom, TimeTo, Location, Desc, Detectors, DetectorNos, Question1, Question2, SpecialPrec, OfficerSign, OfficerName, OfficerPos, CheifSign, CheifName, CaptainSign, CaptainName, PrecAddedBy, PrecBox) values(#Username, #Ship, #Date, #TimeFrom, #TimeTo, #Location, #Desc, #Detectors, #DetectorNos, #Question1, #Question2, #SpecialPrec, #OfficerSign, #OfficerName, #OfficerPos, #CheifSign, #CheifName, #CaptainSign, #CaptainName, #PrecAddedBy, #PrecBox);";
MySqlConnection con = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, con);
cmdDatabase.Parameters.Add("#Username", MySqlDbType.VarChar, 50).Value = login.username;
cmdDatabase.Parameters.Add("#Ship", MySqlDbType.VarChar, 50).Value = txtbox_ship.Text;
cmdDatabase.Parameters.Add("#Date", MySqlDbType.VarChar, 50).Value = txtbox_date.Text;
cmdDatabase.Parameters.Add("#TimeFrom", MySqlDbType.VarChar, 50).Value = txtbox_timeFrom.Text;
cmdDatabase.Parameters.Add("#TimeTo", MySqlDbType.VarChar, 50).Value = txtbox_timeTo.Text;
cmdDatabase.Parameters.Add("#Location", MySqlDbType.VarChar, 50).Value = txtbox_location;
cmdDatabase.Parameters.Add("#Desc", MySqlDbType.VarChar, 50).Value = txtbox_work_desc.Text;
cmdDatabase.Parameters.Add("#Detectors", MySqlDbType.VarChar, 50).Value = detector;
cmdDatabase.Parameters.Add("#DetectorNos", MySqlDbType.VarChar, 50).Value = txtbox_detector_desc.Text;
cmdDatabase.Parameters.Add("#Question1", MySqlDbType.VarChar, 50).Value = questions;
cmdDatabase.Parameters.Add("#Question2", MySqlDbType.VarChar, 50).Value = question2;
cmdDatabase.Parameters.Add("#SpecialPrec", MySqlDbType.VarChar, 50).Value = txtbox_precautions.Text;
cmdDatabase.Parameters.Add("#OfficerSign", MySqlDbType.VarChar, 50).Value = txtbox_officer_sign.Text;
cmdDatabase.Parameters.Add("#OfficerName", MySqlDbType.VarChar, 50).Value = txtbox_officer_name.Text;
cmdDatabase.Parameters.Add("#OfficerPos", MySqlDbType.VarChar, 50).Value = txtbox_officer_pos.Text;
cmdDatabase.Parameters.Add("#CheifSign", MySqlDbType.VarChar, 50).Value = txtbox_cheif_sign.Text;
cmdDatabase.Parameters.Add("#CheifName", MySqlDbType.VarChar, 50).Value = txtbox_cheif_name.Text;
cmdDatabase.Parameters.Add("#CaptainSign", MySqlDbType.VarChar, 50).Value = txtbox_captain_sign.Text;
cmdDatabase.Parameters.Add("#CaptainName", MySqlDbType.VarChar, 50).Value = txtbox_captain_name.Text;
cmdDatabase.Parameters.Add("#PrecAddedBy", MySqlDbType.VarChar, 50).Value = capOrCheif;
cmdDatabase.Parameters.Add("#PrecBox", MySqlDbType.VarChar, 50).Value = txtbox_restrictions.Text;
MySqlDataReader myReader;
if (cbox_read.Checked == true)
{
con.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
}
MessageBox.Show("Hot Work Permit Form has been sent to the Cheif Engineer");
}
else
{
MessageBox.Show("You have to read it through and accept it!");
}
}

DATE is not a reserved word, despite the comment above. You can get a list of reserved words here: https://dev.mysql.com/doc/refman/8.0/en/keywords.html
That page lists keywords, but only a subset of those are reserved, indicated by the (R) annotation in the list.
The error message tells you which word caused the parser to become confused:
...check the manual that corresponds to your MySQL server version for the right syntax to use near 'Desc, Detectors, ...
It got confused on the word DESC. Syntax errors in MySQL always show you the portion of the query starting at the point where it got confused.
DESC is the reserved word causing a problem in this case. DESC has the (R) annotation in the keywords list I linked to.
You should delimit identifiers that conflict with reserved words:
string Query = "INSERT INTO tbl_permit (... Location, `Desc`, Detectors, ...

Related

Passing userID into columns of same table and another table

I am trying to insert record into two tables and fetch the UserId of first table and insert into another column of the same table and also into another table but it appears that when I insert data into the tables, the Id of the user is returned and inserted into the second table but inserted a different integer into another column of same first table.
For example, I have UserTable and WalletTable and I want to insert records simultaneously into the two tables and at the same time fetch the Id of UserTable and insert into columns of both tables.
Here is the structure of the first table: I want to fetch UserID in UserTable and insert into CreatedBy of UserTable and UserID of WalletTable. But after inserting, I discovered that integer -1 is inserted into the CreatedBy column of UserTable and in WalletTable the correct UserID is inserted.
How can I correct this please?
UserTable:
UserID | email | pass | con_pass | UserRole | Name | CreatedBy | image | CreateDate
WalletTable:
Id | UserID | email | Name | amount
Here is my insert code (C#)
if (mailtxtbx.Text != "" & pass.Text != "" & conpass.Text != "" & txtname.Text !="")
{
if (pass.Text == conpass.Text)
{
if (Filedoc.PostedFile.FileName != "")
{
if (check1.Checked)
{
int Uid = -1;
byte[] image;
Stream s = Filedoc.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
image = br.ReadBytes((Int32)s.Length);
// define query to be executed
string query = #"INSERT INTO Users (email, pass, con_pass, UserRole, Name, CreatedBy, image, CreateDate) VALUES (#email, #pass, #con_pass, #UserRole, #Name, #CreatedBy, #image, #CreateDate);
SELECT SCOPE_IDENTITY();";
// set up SqlCommand in a using block
using (SqlCommand objCMD = new SqlCommand(query, con))
{
// add parameters using regular ".Add()" method
objCMD.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = mailtxtbx.Text.Trim();
objCMD.Parameters.Add("#pass", SqlDbType.VarChar, 100).Value = pass.Text.Trim();
objCMD.Parameters.Add("#con_pass", SqlDbType.VarChar, 50).Value = conpass.Text.Trim();
objCMD.Parameters.Add("#UserRole", SqlDbType.VarChar, 50).Value = 'A';
objCMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = txtname.Text.Trim();
objCMD.Parameters.Add("#CreatedBy", SqlDbType.Int, 50).Value = Uid;
objCMD.Parameters.Add("#image", SqlDbType.VarBinary).Value = image;
objCMD.Parameters.Add("#CreateDate", SqlDbType.DateTime, 100).Value = DateTime.Now;
// open connection, execute query, close connection
con.Open();
object returnObj = objCMD.ExecuteScalar();
if (returnObj != null)
{
int.TryParse(returnObj.ToString(), out Uid);
}
cmd.ExecuteNonQuery();
}
con.Close();
if (Uid > 0)
{
query = #"INSERT INTO UserWallet (Uid, email, Name, amount) VALUES (#Uid, #email, #Name, #amount)";
using (SqlCommand objCMD = new SqlCommand(query, con))
{
// add parameters using regular ".Add()" method
objCMD.Parameters.Add("#Uid", SqlDbType.Int, 50).Value = Uid;
objCMD.Parameters.Add("#email", SqlDbType.VarChar, 50).Value = mailtxtbx.Text.Trim();
objCMD.Parameters.Add("#Name", SqlDbType.VarChar, 50).Value = txtname.Text.Trim();
objCMD.Parameters.Add("#amount", SqlDbType.Float, 100).Value = 0; //Change type here accordingly
con.Open();
object returnObj = objCMD.ExecuteScalar();
if (returnObj != null)
{
int.TryParse(returnObj.ToString(), out Uid);
}
cmd.ExecuteNonQuery();
lblsuccess.Visible = true;
Div1.Visible = true;
lblsuccess.Text = "Successfully signed up";
lblsuccess.ForeColor = System.Drawing.Color.Green;
lblMessage.Visible = false;
dvMessage.Visible = false;
mailtxtbx.Text = "";
pass.Text = "";
conpass.Text = "";
txtname.Text = "";
// Response.Redirect("Default.aspx");
}
}
con.Close();
}
}
}
}

Inserting multiple Values into Microsoft SQL Server via C#

I have a database made up of 2 (more, actually, but only 2 im working with) tables.
The Material table consists solely of the material-number and the description
DPMatNr
DPBezeichnung
The Eigenschaften table is there to hold the properties of the materials.
It uses the columns:
EigenschaftenBezeichnerID
Wert (value)
My problem is: each entry in the Material table needs to have multiple entries in the Eigenschaften table.
For example:
"Material":
DPMatNr = 001,
DPBezeichnung = "Description"
"Eigenschaften":
EigenschaftenBezeichnerID = 1,
Wert = "A4"
EigenschaftenBezeichnerID = 3,
Wert = "80" and so on.
My code currently looks like this:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string query = #"Insert INTO dbo.Material (DPMatNr, DPBezeichnung)
VALUES (#matnummer, #bezeichnung)";
string query2 = #"Insert INTO dbo.Eigenschaften
(EigenschaftenBezeichnerID, Wert)
VALUES (#1, #format, #2, #grammatur, #3, #gewicht,
#4, #eform, #5, #kuvertierung,
#6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cn.Open();
cmd.ExecuteNonQuery();
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}
Now I currently get an error that says:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Material' with unique index 'IX_MatNrUnique'
What am I doing wrong?
The Problem here is, that for every "Eigenschaft" you insert into the table you also try to create an entry in the "Material" table. But since every material should only be inserted once (therefore the primary key) you get the error.
Edit:
You could adjust your method like the following:
public static void InsertData(string connectionstring, string matnummer, string bezeichnung, string format, string grammatur, string gewicht, string eform, string kuvertierung, string altkuvert)
{
string check = "Select COUNT(*) FROM dbo.Material where DPMatNr = #matnummer";
string query = "Insert INTO dbo.Material (DPMatNr, DPBezeichnung)" + "VALUES (#matnummer, #bezeichnung)";
string query2 = "Insert INTO dbo.Eigenschaften (EigenschaftenBezeichnerID, Wert)" + "VALUES (#1, #format, #2, #grammatur, #3, #gewicht, #4, #eform, #5, #kuvertierung, #6, #altkuvert)";
using (SqlConnection cn = new SqlConnection(connectionstring))
using (SqlCommand chkCom = new SqlCommand(check, cn))
{
cn.Open();
chkCom.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
int? matCnt = chkCom.ExecuteScalar() as int?;
if (matCnt == 0 || matCnt == null)
{
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.Add("#matnummer", SqlDbType.VarChar, 50).Value = matnummer;
cmd.Parameters.Add("#bezeichnung", SqlDbType.VarChar, 50).Value = bezeichnung;
cmd.ExecuteNonQuery();
}
}
using (SqlCommand cmd2 = new SqlCommand(query2, cn))
{
cmd2.Parameters.Add("#1", SqlDbType.Int).Value = 1;
cmd2.Parameters.Add("#format", SqlDbType.VarChar, 50).Value = format;
cmd2.Parameters.Add("#2", SqlDbType.Int).Value = 2;
cmd2.Parameters.Add("#grammatur", SqlDbType.VarChar, 50).Value = grammatur;
cmd2.Parameters.Add("#3", SqlDbType.Int).Value = 3;
cmd2.Parameters.Add("#gewicht", SqlDbType.VarChar, 50).Value = gewicht;
cmd2.Parameters.Add("#4", SqlDbType.Int).Value = 4;
cmd2.Parameters.Add("#eform", SqlDbType.VarChar, 50).Value = eform;
cmd2.Parameters.Add("#5", SqlDbType.Int).Value = 5;
cmd2.Parameters.Add("#kuvertierung", SqlDbType.VarChar, 50).Value = kuvertierung;
cmd2.Parameters.Add("#6", SqlDbType.Int).Value = 6;
cmd2.Parameters.Add("#altkuvert", SqlDbType.VarChar, 50).Value = altkuvert;
cmd2.ExecuteNonQuery();
}
cn.Close();
}
}

I want to Insert RadioButton Value in SQL Database using Classes

I created a Class name EmployeeDAta write this code here and i want to Insert Radiobutton value in SQL Database
public static void AddEmployee(Employee employee)
{
string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
using (conn)
{
SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar, 50).Value = employee.Name;
cmd.Parameters.Add("#FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar, 50).Value = employee.Address;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar, 50).Value = employee.Email;
cmd.Parameters.Add("#Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
cmd.Parameters.Add("#Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
cmd.Parameters.AddWithValue("#VB", SqlDbType.Bit).Value = employee.VB;
cmd.Parameters.AddWithValue("#ASP", SqlDbType.Bit).Value = employee.ASP;
cmd.Parameters.AddWithValue("#Gender", SqlDbType.Int).Value = employee.Gender;
conn.Open();
cmd.ExecuteNonQuery();
}
}
add a parameter to your stored procedure call:
cmd.Parameters.AddWithValue("#ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;
In the stored procedure on the database, make sure you handle the extra parameter.

Insert Collection into SQL Server Table in C#

Trying to insert a collection into a table in SQL Server 2014. Here's my code it executes without error but when I check my table - nothing is added. My collection object orders isn't empty either I can see it has 3 members when debugging it.
IEnumerable<CompleteOrderDetails> orders;
JoinDetails(doc, ns, xmlFragment1, out orders);
string connectionstring = null;
SqlConnection conn;
connectionstring = "Data Source = DANNY; Initial Catalog = Alliance; Integrated Security = SSPI";
using (conn = new SqlConnection(connectionstring))
{
string customerInsert = "INSERT INTO AmazonCustomer (AddressLine1, AddressLine2, AddressLine3, City, StateOrRegion, AmazonOrderId, PostalCode, Title, ItemPrice, ShippingPrice, Quantity) " +
"VALUES (#AddressLine1, #AddressLine2, #AddressLine3, #City, #StateOrRegion, #AmazonOrderId, #PostalCode, #Title, #ItemPrice, #ShippingPrice, #Quantity)";
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
foreach (var order in orders)
{
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150).Value = order.AmazonOrderId;
query.Parameters.Add("#Name", SqlDbType.NVarChar, 150).Value = order.Name;
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150).Value = order.AddressLine1;
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150).Value = order.AddressLine2;
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150).Value = order.AddressLine3;
query.Parameters.Add("#City", SqlDbType.NVarChar, 150).Value = order.City;
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150).Value = order.StateOrRegion;
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150).Value = order.PostalCode;
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150).Value = order.Title;
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150).Value = order.ItemPrice;
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150).Value = order.ShippingPrice;
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150).Value = order.Quantity;
}
conn.Open();
conn.Close();
}
}
Code Edits from Comments
private static void ExecuteSqlTransaction(IEnumerable<CompleteOrderDetails> orders)
{
string connectionstring = null;
SqlConnection conn;
SqlTransaction transaction;
connectionstring = "Data Source = DANNY; Initial Catalog = Alliance; Integrated Security = SSPI";
using (conn = new SqlConnection(connectionstring))
{
conn.Open();
transaction = conn.BeginTransaction("Transaction");
string customerInsert =
"INSERT INTO AmazonCustomer (Name, AddressLine1, AddressLine2, AddressLine3, City, StateOrRegion, AmazonOrderId, PostalCode, Title, ItemPrice, ShippingPrice, Quantity) VALUES (#Name, #AddressLine1, #AddressLine2, #AddressLine3, #City, #StateOrRegion, #AmazonOrderId, #PostalCode, #Title, #ItemPrice, #ShippingPrice, #Quantity)";
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
query.Transaction = transaction;
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Name", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150);
query.Parameters.Add("#City", SqlDbType.NVarChar, 150);
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150);
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150);
try
{
foreach (var order in orders)
{
query.Parameters["#AmazonOrderId"].Value = order.AmazonOrderId ?? Convert.DBNull;
query.Parameters["#Name"].Value = order.Name ?? Convert.DBNull;
query.Parameters["#AddressLine1"].Value = order.AddressLine1 ?? Convert.DBNull;
query.Parameters["#AddressLine2"].Value = order.AddressLine2 ?? Convert.DBNull;
query.Parameters["#AddressLine3"].Value = order.AddressLine3 ?? Convert.DBNull;
query.Parameters["#City"].Value = order.City ?? Convert.DBNull;
query.Parameters["#StateOrRegion"].Value = order.StateOrRegion ?? Convert.DBNull;
query.Parameters["#PostalCode"].Value = order.PostalCode ?? Convert.DBNull;
query.Parameters["#Title"].Value = order.Title ?? Convert.DBNull;
query.Parameters["#ItemPrice"].Value = order.ItemPrice ?? Convert.DBNull;
query.Parameters["#ShippingPrice"].Value = order.ShippingPrice ?? Convert.DBNull;
query.Parameters["#Quantity"].Value = order.Quantity ?? Convert.DBNull;
query.ExecuteNonQuery();
transaction.Commit();
}
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
}
You open and close the connection without actually executing anything.
Also, move the adding of the parameters outside of your foreach loop and just set the values within the loop.
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Name", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150);
query.Parameters.Add("#City", SqlDbType.NVarChar, 150);
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150);
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150);
conn.Open();
foreach (var order in orders)
{
query.Parameters["#AmazonOrderId"].Value = order.AmazonOrderId;
query.Parameters["#Name"].Value = order.Name;
query.Parameters["#AddressLine1"].Value = order.AddressLine1;
query.Parameters["#AddressLine2"].Value = order.AddressLine2;
query.Parameters["#AddressLine3"].Value = order.AddressLine3;
query.Parameters["#City"].Value = order.City;
query.Parameters["#StateOrRegion"].Value = order.StateOrRegion;
query.Parameters["#PostalCode"].Value = order.PostalCode;
query.Parameters["#Title"].Value = order.Title;
query.Parameters["#ItemPrice"].Value = order.ItemPrice;
query.Parameters["#ShippingPrice"].Value = order.ShippingPrice;
query.Parameters["#Quantity"].Value = order.Quantity;
query.ExecuteNonQuery();
}
conn.Close();
}
Apart from the obvious error of the missing ExecuteNonQuery call, your code will fail again because you add the parameters at each loop. This will lead to an exception caused by a parameter already defined.
You need to clear the parameters collection with
cmd.Parameters.Clear();
at the start of each loop or better define the parameters before the loop and, inside the loop, change only the values
using (conn = new SqlConnection(connectionstring))
{
string customerInsert = #"INSERT INTO AmazonCustomer
(AddressLine1, AddressLine2, AddressLine3, City,
StateOrRegion, AmazonOrderId, PostalCode, Title,
ItemPrice, ShippingPrice, Quantity)
VALUES (#AddressLine1, #AddressLine2, #AddressLine3, #City,
#StateOrRegion, #AmazonOrderId, #PostalCode, #Title,
#ItemPrice, #ShippingPrice, #Quantity)";
using (SqlCommand query = new SqlCommand(customerInsert))
{
query.Connection = conn;
// Not used ???
// query.Parameters.Add("#Name", SqlDbType.NVarChar, 150)
query.Parameters.Add("#AddressLine1", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine2", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AddressLine3", SqlDbType.NVarChar, 150);
query.Parameters.Add("#City", SqlDbType.NVarChar, 150);
query.Parameters.Add("#StateOrRegion", SqlDbType.NVarChar, 150);
query.Parameters.Add("#AmazonOrderId", SqlDbType.NVarChar, 150);
query.Parameters.Add("#PostalCode", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Title", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ItemPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#ShippingPrice", SqlDbType.NVarChar, 150);
query.Parameters.Add("#Quantity", SqlDbType.NVarChar, 150);
conn.Open();
using(SqlTransaction tr = conn.BeginTransaction())
{
foreach (var order in orders)
{
// Not used ???
// query.Parameters["#Name"].Value = order.Name;
query.Parameters["#AddressLine1"].Value = order.AddressLine1;
query.Parameters["#AddressLine2"].Value = order.AddressLine2;
query.Parameters["#AddressLine3"].Value = order.AddressLine3;
query.Parameters["#City"].Value = order.City;
query.Parameters["#StateOrRegion"].Value = order.StateOrRegion;
query.Parameters["#AmazonOrderId"].Value = order.AmazonOrderId;
query.Parameters["#PostalCode"].Value = order.PostalCode;
query.Parameters["#Title"].Value = order.Title;
query.Parameters["#ItemPrice"].Value = order.ItemPrice;
query.Parameters["#ShippingPrice"].Value = order.ShippingPrice;
query.Parameters["#Quantity"].Value = order.Quantity;
query.ExecuteNonQuery();
}
tr.Commit();
}
}
}
Notice that the connection could be opened at the start of the loop and not at each loop, while the using statement take cares to close and dispose it, and given the nature of your inserts, I suggest also to encapsulate everything inside a SqlTransaction so your code is more 'atomic'.
Finally something is not correct in your query, there is a parameter placeholder that has not matching parameter in the collection (#ID) and there is a parameter that has no placeholder in the query (#name). Without fixing these two errors you get other errors. I have removed them from the query and from the parameters collection

Am I protected against SQL injections?

I have been attacked on my last few questions here for writing code that is open to injections. I am looking for honest help to make sure I am finally doing this the safest and correct way. Please give me any tips to make this as secure as possible.
using (SqlConnection conn = new SqlConnection(""))
{
try
{
SqlCommand cmd = new SqlCommand(#"INSERT dbo.Table (FullName, Category, Street, City, State, Zip, PhoneDay, PhoneEven, Email, Employer, Description, UserName,
UserStreet, UserCity, UserState, UserZip, UserPhoneDay, UserPhoneEven, UserEmail, SubmitDate)
VALUES (#f1, #f2, #f3, #f4, #f5, #f6, #f7, #f8, #f9, #f10, #f11, #f12, #f13, #f14, #f15, #f16, #f17, #f18, #f19, #f20)", conn);
conn.Open();
cmd.Parameters.Add("#f1", SqlDbType.NVarChar, 100).Value = NameTxtBox.Text;
cmd.Parameters.Add("#f2", SqlDbType.NVarChar, 100).Value = HeroicList.SelectedValue;
cmd.Parameters.Add("#f3", SqlDbType.NVarChar, 100).Value = StreetTxtBox.Text;
cmd.Parameters.Add("#f4", SqlDbType.NVarChar, 100).Value = CityTxtBox.Text;
cmd.Parameters.Add("#f5", SqlDbType.NVarChar, 100).Value = StateTxtBox.Text;
cmd.Parameters.Add("#f6", SqlDbType.NVarChar, 100).Value = ZipTxtBox.Text;
cmd.Parameters.Add("#f7", SqlDbType.NVarChar, 100).Value = PhoneDayTxtBox.Text;
cmd.Parameters.Add("#f8", SqlDbType.NVarChar, 100).Value = PhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f9", SqlDbType.NVarChar, 100).Value = EmailTxtBox.Text;
cmd.Parameters.Add("#f10", SqlDbType.NVarChar, 100).Value = EmpTxtBox.Text;
cmd.Parameters.Add("#f11", SqlDbType.NVarChar, 100).Value = WhyTxtBox.Text;
cmd.Parameters.Add("#f12", SqlDbType.NVarChar, 100).Value = UserNameTxtBox.Text;
cmd.Parameters.Add("#f13", SqlDbType.NVarChar, 100).Value = UserStreetTxtBox.Text;
cmd.Parameters.Add("#f14", SqlDbType.NVarChar, 100).Value = UserCityTxtBox.Text;
cmd.Parameters.Add("#f15", SqlDbType.NVarChar, 100).Value = UserStateTxtBox.Text;
cmd.Parameters.Add("#f16", SqlDbType.NVarChar, 100).Value = UserZipTxtBox.Text;
cmd.Parameters.Add("#f17", SqlDbType.NVarChar, 100).Value = UserPhoneDayTxtBox.Text;
cmd.Parameters.Add("#f18", SqlDbType.NVarChar, 100).Value = UserPhoneEvenTxtBox.Text;
cmd.Parameters.Add("#f19", SqlDbType.NVarChar, 100).Value = UserEmailTxtBox.Text;
cmd.Parameters.Add("#f20", SqlDbType.DateTime).Value = DateTime.Now.ToString();
cmd.ExecuteNonQuery();
messageLabel.Text = "Your submission has been sent!";
messageLabel.Visible = true;
}
catch (System.Data.SqlClient.SqlException ex)
{
messageLabel.Text = ex.Message;
messageLabel.Visible = true;
}
}
You're protected with respect to insertion, yes. Using your code, it doesn't matter what the user puts in any of the textboxes (or what they put in any other sort of response they can cook up) nothing will happen beyond their data being stuck into fields of a new row of the given table, exactly as the strings were given to you.
The only way (that comes to mind) that someone could maliciously inject code would depend on how you use the data once it's in the database. If you go and, for example, take a field from this table and stick it in a LiteralControl without escaping anything and show it to other users then someone could stick in nasty JavaScript code that they run on another person's machine, for example. That would be a "cross site scripting" attack. To prevent that you need to make sure that any user-inputted data is sanitized before being displayed.

Categories

Resources