How to insert data into two tables - c#

I want to know how to insert data into two different tables.
I have
Orders table, which has:
OrderID, info, Price, VAT, Customer_ID
and Customer table
CustomerID, Name, LastName
Now i want to enter new order, which would have primary key of 1.
How can i write SQL that would enter this order for specific person,..let's say a person who has id of 1 in customer table?
This is what i have so far, but i just can't find solution
using (SqlCommand cmd = new SqlCommand("INSERT INTO [Orders] (info, Price, VAT, Customer_ID) VALUES (#info, #Price, #VAT, #Customer_ID)"))
{
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#info", input1.Text);
cmd.Parameters.AddWithValue("#Price", input2.Text);
cmd.Parameters.AddWithValue("#VAT", input3.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
UPDATE
i don't want to enter foreign key(id) via textbox, but get it from current logged in user...

Unless I'm misunderstanding your question it should be a simple matter of adding another parameter.
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [Orders] (info, Price, VAT, Customer_ID) VALUES (#info, #Price, #VAT, #Customer_ID)"))
{
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#info", input1.Text);
cmd.Parameters.AddWithValue("#Price", input2.Text);
cmd.Parameters.AddWithValue("#VAT", input3.Text);
cmd.Parameters.AddWithValue("#Customer_ID", input4.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
If you do not have the customer_ID as an input field and want to make it always create an order for customer "1" then do the following
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [Orders] (info, Price, VAT, Customer_ID) VALUES (#info, #Price, #VAT, 1)"))
{
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#info", input1.Text);
cmd.Parameters.AddWithValue("#Price", input2.Text);
cmd.Parameters.AddWithValue("#VAT", input3.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
If instead you are wanting to do something a bit more dynamic with looking up which customer an order is for we will need more information about your data input first. You'd need to do a select query to find the customer_ID and then pass that in as a parameter or just sub-select within the insert query.
EDIT:
Here's code using the dynamic query as you mentioned in the comments
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO [Orders] (info, Price, VAT, Customer_ID) SELECT #info, #Price, #VAT, CustomerID FROM Customer WHERE Name = #Username)"))
{
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#info", input1.Text);
cmd.Parameters.AddWithValue("#Price", input2.Text);
cmd.Parameters.AddWithValue("#VAT", input3.Text);
cmd.Parameters.AddWithValue("#Username", SomeVariableWithUsername);
conn.Open();
cmd.ExecuteNonQuery();
}

Could it be that your parametry is missing?
cmd.Parameters.AddWithValue("#Customer_ID", input4.Text);

Related

How to insert into specific columns of a database

The problem is am getting an exception error that says data mismatch in the external database when i try to insert
I have a customer booking table with booking id ...pk as auto number, customer.... fk and date in as datetime
Booking id is auto increment so i don't need to insert anything
What i want to achieve is to insert into customer_id and date in thats all but i keep getting the data mismatch and number of query valuesis not the same as destination fields
So what is the right way to put this
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (?,?)";
cmd.Parameters.AddWithValue("#customer_id", txtusername.Text);
cmd.Parameters.AddWithValue("#date_in", dtdate_in);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
use cmd.Parameters.add('...') method as follow :
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (#customer_id,#date_in)";
///* Set your column dataType*/
cmd.Parameters.Add("#customer_id", SqlDbType.VarChar , 50).Value = txtusername.Text;
cmd.Parameters.Add("#date_in", SqlDbType.DateTime).Value = dtdate_in;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}

Trying to insert int variable into SQL Server table

protected void addItem_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string PID;
Button oButton = (Button)sender;
PID = oButton.CommandArgument.ToString();
int productId = Convert.ToInt32(PID);
Debug.Write(productId);
string email = (string)(Session["email"]);
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
When my query executes, I get an error
Invalid column name 'productId'
As you can see, I have converted a string into an integer variable, I have printed off the variable to check what it is returning. It does return a int as expected, but for some odd reason i can not insert into to my table. Any help would be great.
Hope productId is not the primary key of the basket table.
Then,instead of
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
Modify like below
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( #productId,#email)", con);
cmd.Parameters.Add(new SqlParameter("#productId",productId );
cmd.Parameters.Add(new SqlParameter("#email",email );
Why suggested to modify is to avoid SQLInjection attack. If you are unaware about that please go through the below link and learn it
https://en.wikipedia.org/wiki/SQL_injection
Two issues here, number 1, and a big one, parameterize that query! You're opening yourself up to SQL injection attacks with code like that.
The second is that you're not actually passing in your productId variable, you're telling it to use the value for the productId column - which is also the column you're trying to insert into.
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values (#productId, #email)");
cmd.Parameters.AddWithValue("#productId", productId);
cmd.Parameters.AddWithValue("#email", email);
I can't stress enough how dangerous it is to dump user input into SQL that's going to be run directly on your database.

How to use last insert id pass to another table

How to use last insert id pass to another table
i have two table 1.product 2.stock i have enclosed with images below.
stack table proid is last insert id come from product table which should add on stock table but
i couldn't add please see the code i tried below
MySqlCommand cm1 = new MySqlCommand();
cm1.Connection = con;
cm1.CommandText = "insert into products(name,qty,price) values (#name,#qty,#price)";
cm1.Parameters.AddWithValue("#name", textBox1.Text);
cm1.Parameters.AddWithValue("#qty", textBox3.Text);
cm1.Parameters.AddWithValue("#price", textBox4.Text);
con.Open();
// Return the id of the new record. Convert from Int64 to Int32 (int).
// return Convert.ToInt32(cm1.Parameters["#newId"].Value);
MySqlCommand cm = new MySqlCommand();
cm.Connection = con;
cm.CommandText = "insert into stock(caname,qty,price) values (#caname,#qty,#price)";
//cm.CommandText = "insert into products(name,qty,price) values (#caname,#qty,#price)";
// cm.Parameters.AddWithValue("#name", textBox1.Text);
// cm.Parameters.AddWithValue("#proid", id);
cm.Parameters.AddWithValue("#caname", textBox2.Text);
cm.Parameters.AddWithValue("#qty", textBox3.Text);
cm.Parameters.AddWithValue("#price", textBox4.Text);
cm.ExecuteNonQuery();
cm1.ExecuteNonQuery();

Assign Primary Key of Table 1 as a Foreign Key in Table 2 using SQL and C#

I have tables Member and Office which use an auto-increment primary key, Member_Id and Office_Id. I am inserting data into the tables but would like to have primary key of the Member table inserted on the Office Table as a foreign key, so that a member is assigned to an office record. Please assist. Below is a snippet of my code for inserting the records but I just do not know how to link the two tables.
protected void capture()
{
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
SqlCommand com = new SqlCommand();
SqlParameter myParam = new SqlParameter();
com.CommandText = "INSERT into Member(Appointment_Number, Initials, Surname, Designation) VALUES (#Appointment_Number, #Initials, #Surname, #Designation)";
com.Parameters.AddWithValue("#Appointment_Number", txtAppointmentNumber.Text);
com.Parameters.AddWithValue("#Initials", txtInitials.Text);
com.Parameters.AddWithValue("#Surname", txtSurname.Text);
com.Parameters.AddWithValue("#Designation", ddlDesignation.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
//Insert records into the office table
com.CommandText = "INSERT into Offices(Office_Number, Status, Building, Branch, Floor) VALUES (#Office_Number, #Status, #Building, #Branch, #Floor)";
com.Parameters.AddWithValue("#Office_Number", txtOffNo.Text);
com.Parameters.AddWithValue("#Status", ddlOStatus.Text);
com.Parameters.AddWithValue("#Building", ddlBuilding.Text);
com.Parameters.AddWithValue("#Branch", ddlBranch.Text);
com.Parameters.AddWithValue("#Floor", ddlFloors.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
if (IsPostBack)
{
Response.Redirect("~/Pages/MemberDetails.aspx");
}
}
}
I think, you want to set a relation between offices and members 1 to n.
So to do that, lets add officeid field in members table, insert the office record before the member and change the code like this;
protected void capture()
{
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
conn.Open();
SqlCommand com = new SqlCommand();
SqlParameter myParam = new SqlParameter();
//Insert records into the office table
com.CommandText = "INSERT into Offices(Office_Number, Status, Building, Branch, Floor) VALUES (#Office_Number, #Status, #Building, #Branch, #Floor)";
com.Parameters.AddWithValue("#Office_Number", txtOffNo.Text);
com.Parameters.AddWithValue("#Status", ddlOStatus.Text);
com.Parameters.AddWithValue("#Building", ddlBuilding.Text);
com.Parameters.AddWithValue("#Branch", ddlBranch.Text);
com.Parameters.AddWithValue("#Floor", ddlFloors.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
com.CommandText = "select max(Office_Id) from Offices";
int officeid = Convert.ToInt32(com.ExecuteScalar());
com.CommandText = "INSERT into Member(officeid,Appointment_Number, Initials, Surname, Designation) VALUES (#officeid,#Appointment_Number, #Initials, #Surname, #Designation)";
com.Parameters.AddWithValue("#officeid", officeid);
com.Parameters.AddWithValue("#Appointment_Number", txtAppointmentNumber.Text);
com.Parameters.AddWithValue("#Initials", txtInitials.Text);
com.Parameters.AddWithValue("#Surname", txtSurname.Text);
com.Parameters.AddWithValue("#Designation", ddlDesignation.Text);
com.Connection = conn;
com.ExecuteNonQuery();
com.Parameters.Clear();
if (IsPostBack)
{
Response.Redirect("~/Pages/MemberDetails.aspx");
}
}
}
Once you've inserted into your first table, using the same connection, SELECT SCOPE_IDENTITY() to get the auto-assigned identity value just created. You can then use that to insert into the second table.
Using SCOPE_IDENTITY() will ensure that you always get the id that you just created. If your system is being used by multiple users concurrently, you don't want to risk picking up the identity value created by another user that happened to be inserting data at the same time as you.
e.g. after your first insert:
com.CommandText = "SELECT SCOPE_IDENTITY()";
int my_id_just_created = Convert.ToInt32(com.ExecuteScalar());
The simplest way to do this is probably to insert your Office table first, get the scope identity, and put that in the FK of you member insert. To get the scope identity just use this syntax :
INSERT INTO YourTable
(val1, val2, val3 ...)
VALUES(#val1, #val2, #val3...);
SELECT SCOPE_IDENTITY();
Then you use com.ExecuteScalar() that will return you an Int with the PK of the Office table that you can use as the FK of the Member table.

Read Id of last inserted

I have been through everything for a couple weeks now only to find statements working at the database level. Below is my code and I feel that I am very near the answer but keep getting -1 returned from SCOPE_IDENTITY(). Customer_Name is saving to the table just fine along with the auto increment. I just need the Customer_ID so that I can place it in the Customer_Address table for the one to many identification of the address to the customer.
Thanks in advance for your help.
if (customer_ID == "")
{
// add new customer
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name)";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
// get last inserted Customer_ID
string SQL_customerId = "SELECT SCOPE_IDENTITY()";
SqlCommand sqlCommand_customerId = new SqlCommand(SQL_customerId, sqlConnection);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlCommand_customerId.ExecuteNonQuery();
// string SQL_ = "SELECT Customer_ID FROM Customer";
// SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
// int maxId = Convert.ToInt32(sqlCommand.ExecuteScalar());
sqlConnection.Close();
}
You need to have the SCOPE_IDENTITY within the same transaction as your insert. The following should help you.
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name); SELECT Customer_Id FROM Customer WHERE Customer_Id = SCOPE_IDENTITY();";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int id = (int) sqlCommand.ExecuteScalar();
try something like this..
Output clause will help you to get the inserted value and with that we can insert into another temp or physical table. This is just an idea to your question
CREATE TABLE customer
(
id INT IDENTITY(1, 1),
addres VARCHAR(500)
)
CREATE TABLE customeraddrs
(
custid INT
)
INSERT INTO customer
output inserted.id
INTO customeraddrs
VALUES ('a'),
('b')
SELECT *
FROM customer
SELECT *
FROM customeraddrs

Categories