How to use last insert id pass to another table - c#

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();

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);
}

How to insert data into two tables

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);

Failed to convert parameter value from a DataRowView to a Int32

I'm inserting records and one of my object is combobox. The combox is connected to the table. When i'm inserting this error appear:
Failed to convert parameter value from a DataRowView to a Int32
My code:
cn.Open();
SqlCommand Insert = new SqlCommand();
Insert.Connection = cn;
Insert.CommandType = CommandType.Text;
Insert.CommandText = "INSERT INTO Ticket VALUES (CustomerID, Date, Store, Amount, NoStub) ";
Insert.Parameters.Add("CustomerID", SqlDbType.Int).Value = cboName.SelectedValue;
Insert.Parameters.Add("Date", SqlDbType.DateTime).Value = dtpDate.Value.Date.ToString();
Insert.Parameters.Add("Store", SqlDbType.NVarChar).Value = txtStore.Text;
Insert.Parameters.Add("Amount", SqlDbType.Decimal).Value = txtAmount.Text;
Insert.Parameters.Add("NoStub", SqlDbType.Decimal).Value = txtStub.Text;
Insert.ExecuteNonQuery();
cn.Close();
Use this sample code:
command.Parameters.Add("#CustomerID", SqlDbType.Int).Value = Convert.ToInt32(storeCode);
or use
int.parse for cboName.
Change your code to the following and let the Server resolve the data type
cn.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = cn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)
VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
sqlCmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
sqlCmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
sqlCmd.Parameters.AddWithValue("#Store", txtStore.Text);
sqlCmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
sqlCmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
sqlCmd.ExecuteNonQuery();
cn.Close();

Save values between 'Steps' in Wizard ASP.NET

I get this error in ASP.NET Wizard when I try to use values of TextBox control of previous step.
Error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Contact_Emp".
The conflict occurred in database "KKSTech", table "dbo.Emp", column 'EmpID'.
Is it a problem to access control's values of different steps?
This is the First class that inserts into dbo.Emp table
public void InsertInfo()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String insertstring = #"insert into Emp (EmpID, FirstName, LastName, MiddleName, Mob1, Mob2, Phone, Email1, Email2, EmpDesc)
values (#EmpID, #FirstName, #LastName, #MiddleName, #Mob1, #Mob2)";
SqlCommand cmd = new SqlCommand(insertstring, conn);
cmd.CommandText = insertstring;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.Parameters.AddWithValue("#FirstName", TextBox2.Text);
cmd.Parameters.AddWithValue("#LastName", TextBox3.Text);
cmd.Parameters.AddWithValue("#MiddleName", TextBox4.Text);
cmd.Parameters.AddWithValue("#Mob1", TextBox5.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox6.Text);
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
And this is the one where I 'm inserting into the table where EmpID is a FK
public void Insertaddress()
{
String KKStech = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True";
SqlConnection conn = new SqlConnection(KKStech);
String str = #"insert into Contact (Addressline1, Addressline2, CityID, EmpID)
values(#Addressline1, #Addressline2, #CityID, #EmpID)";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.CommandText = str;
cmd.CommandType = CommandType.Text;
try
{
conn.Open();
cmd.Parameters.AddWithValue("#Addressline1", TextBox15.Text);
cmd.Parameters.AddWithValue("#Addressline2", TextBox17.Text);
cmd.Parameters.AddWithValue("#CityID", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("#EmpID", TextBox1.Text);
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
That was my problem.
A foreign key ensures that it cannot have a value in that column that is not also in the primary key column of the referenced table.
In your case , you are inserting EmpID into contact table which is not present in the referenced table of EmpID i.e Emp table.

access MDB update data in C# via sql

I've had help here
Inserting and Updating data to MDB
but still have a problem with update
I have an access mdb file with table "Table1" and 3 colums
ID
INFO
TEXT
I can add new info, find info but the update gives me an unknown error. Something is wrong with the command I sent.
con = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = c:\\mdb\\testmdb.mdb");
cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Table1 SET Info = #Info, text = #text WHERE ID = #ID;";
cmd.Parameters.AddWithValue("#ID", textBox1.Text);
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
con.Open(); // open the connection
int numAffected = cmd.ExecuteNonQuery();
con.Close();
The OleDbCommand does not support named parameters. This:
"UPDATE Table1 SET Info = #Info, text = #text WHERE ID = #ID;";
is equivalent to this:
"UPDATE Table1 SET Info = ?, text = ? WHERE ID = ?;";
and when you add parameters to the Parameters collection they are assigned in the order they are added. So the first parameter added will be assigned to the first placeholder, the second parameter to the second etc. You may use names for the placeholders for readability purposes but they do not matter when assigning values.
So you need to change the order in which you add the values to match the order in your query:
cmd.Parameters.AddWithValue("#Info", textBox2.Text);
cmd.Parameters.AddWithValue("#text", textBox3.Text);
cmd.Parameters.AddWithValue("#ID", textBox1.Text);

Categories