How do I Insert records in database multiple Tables using winforms c#
I have a winform which i have attached here.. When i Insert record in Customer table, I also want to add the record in the orderlineitems table in my database 开发者_StackOverflow中文版as of which the record in the Order table will also be inserted. I have inserted the record in Customer table but when i insert record in OrderLineItems table, it shows an error.
I also wanted to ask that, my OrderLineItems Table in database contains columns as :
- ID(pk)
- OrderID(pk)
- Quantity
- Particular
- Rates
- Status
On my Form, I have only quantity, particular and rates fields from which i can get their values but i dont have Status and Orderid values on my winform. how do i get the values of status and orderId then?
My Code is:
private void buttonInsert_Click(object sender, EventArgs e)
{
string SQL = String.Format("Insert into Customer values ('{0}','{1}','{2}')", textBoxName.Text, textBoxContactNo.Text, textBoxAddress.Text);
//string SQL1 = String.Format("Insert into Order values ({0},'{1}','{2}',{3})",);
DataManagementClass dm = new DataManagementClass();
int result = dm.ExecuteActionQuery(SQL);
if (result > 0)
{
for (int i = 0; i < recordsDataGridView.RowCount ; i++)
{
string query = String.Format("Insert into OrderLineItems values({0},'{1}','{2}','{3}',{4})",7,QuantityColumn, ParticularColumn, RatesColumn,1);
dm.ExecuteActionQuery(query);
}
//string query = String.Format("Insert into OrderLineItems values ('{0}','{1},'{2}'
}
What am i doing wrong here. please guide me the correct way. Thanx..
Suggest a few enhancements to get your business logic working and maintainable:
- write a stored procedure for your
CreateCustomer
andCreateLineItem
routines in your database. - use a SqlCommand and its Parameters collection. Stop whatever you're doing right now and guard against SQL injection.
- remove all this code from the button click event.
- create new methods like
CreateCustomer
andCreateLineItems
. Call these method from your button click handler method.
private void buttonInsert_Click(object sender, EventArgs e)
{
int result = CreateCustomer(textBoxName.Text.Trim(),
textBoxContactNo.Text.Trim(),
textBoxAddress.Text.Trim());
if (result > 0)
{
foreach(var row in recordsDataGridView.Rows)
{
CreateLineItem(quantity, particulars, rates);
}
}
You are inserting values like this: '{1}','{2}','{3}'
This leads me to assume you are inserting string values.
If there is an apostroph in your string values, it will cause a syntax error.
Try
yourstring.replace("'", "''")
on the arguments.
Also, do as p.campbell suggest..
Use parameters to prevent SQL injection..
Somebody might malicously take advantage of your code's open security holes..
精彩评论