How to insert primary key in database? - c#

as emp_id is pk and it has no textbox
cmd.CommandText = "INSERT INTO cntc_employee (emp_id,emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#empid", ????);
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
For empid I don't know which command to use
cmd.Parameters.AddWithValue("#empid", ????);

If you want that your empid increased automatically then you have to set the IDENTITY of it.
If you are using MSSQL then use below image to set IDENTITY of table.

If emp_id is an automatically generated Primary Key, simply don't specify it in the column list (and thus there is no reason to supply a binding value) - this includes IDENTITY columns in SQL Server and AUTO_INCREMENT columns in MySQL, etc.
// Additional columns removed for sake of example
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name) values (#fname)";
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
Assuming this is the case, then the database will see that emp_id has not been assigned a value and will use the "next" available value for the column when the record is inserted.
If emp_id is not an automatically generated surrogate Key, then find out who designed the system and ask them what the value should be and how it should be generated :)

If the EmpId is Identity in the SQL then no need to pass it,
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
if it is not then you need to mention or generate the logic in your Programming Language to create the Emp ID

If you realy want to insert a specific value to the field emp_id for some reason, you have to set Identity_insert to on.
// "SET IDENTITY_INSERT [ database_name . [ schema_name ] . ] table { ON | OFF }"
cmd.CommandText = "SET IDENTITY_INSERT dbo.cntc_employee ON; ";
cmd.CommandText += "INSERT INTO cntc_employee (emp_id,emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#empid,#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#empid", textBoxXx.Text);
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
SET IDENTITY_INSERT (Transact-SQL)

Related

ExecuteNonQuery is not running

foreach (GridViewRow g1 in GridView1.Rows)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Order VALUES(#buyersName, #deliveryAddress, #productID, #productName, #category, CONVERT(VARBINARY(MAX), #image), #price, #paymentMode, #holderName)", con);
cmd.Parameters.AddWithValue("#buyersName", Label2.Text);
cmd.Parameters.AddWithValue("#deliveryAddress", TextBox1.Text);
cmd.Parameters.AddWithValue("#productID", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#productName", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#category", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#image", g1.Cells[3].Text);
cmd.Parameters.AddWithValue("#price", g1.Cells[4].Text);
cmd.Parameters.AddWithValue("#paymentMode", checkRadioButton());
cmd.Parameters.AddWithValue("#holderName", TextBox2.Text);
int r = cmd.ExecuteNonQuery();
}
When I run this code, it is showing an error that there is a syntax error near "Order". checkRadioButton() is returning the label of the selected RadioButton.
you can't have expression like convert() within the VALUE ()
Change to use
INSERT INTO [Order] (column name, ...)
select #buyersName, convert() ,...
by the way you should explicitly specify the column name in the INSERT clause or in future when you add a column to the table, your query will break
also why are you using reserved name as table name ?
Contrary to the statement in the other answer, it should be possible to CONVERT within the VALUES-section.
But there are multiple flaws or things that could be improved:
ORDER is a reserved word in sql server, put it in square brackets: [Order]
Don't use AddWithValue otherwise sql server infers the datatype, which could be problematic. Use Add instead. See here for more information.
You can convert the value of g1.Cells[3].Text to a byte-array (byte[]) before setting the parameter value. For conversion to byte[] see here.
Specify the columns in your query, to not break it when table changes in future
Change your code like following (column-names and datatypes may vary):
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Order] (buyersName, deliveryAddress, productID, productName, category, image, price, paymentMode, holderName)
VALUES(#buyersName, #deliveryAddress, #productID, #productName, #category, #image, #price, #paymentMode, #holderName)", con);
cmd.Parameters.Add("#buyersName", SqlDbType.VarChar).Value = Label2.Text;
cmd.Parameters.Add("#deliveryAddress", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("#productID", SqlDbType.VarChar).Value = g1.Cells[0].Text;
cmd.Parameters.Add("#productName", SqlDbType.VarChar).Value = g1.Cells[1].Text;
cmd.Parameters.Add("#category", SqlDbType.VarChar).value = g1.Cells[2].Text;
cmd.Parameters.Add("#image", SqlDbType.VarBinary).Value = g1.Cells[3].Text; //convert g1.Cells[3].Text to a byte array
cmd.Parameters.Add("#price", SqlDbType.Money) = g1.Cells[4].Text;
cmd.Parameters.Add("#paymentMode", SqlDbType.VarChar).Value = checkRadioButton();
cmd.Parameters.Add("#holderName", SqlDbType.VarChar).Value = TextBox2.Text;
int r=cmd.ExecuteNonQuery();

get primary key of recently added record and insert into another table as foreign key

Am using asp.net as front end and MySQL as back end.
I have two tables "Registration" and "User".
I have a registration form, in that i have registration details along with login details.
Wen user click register the registration details is saved to "Registration" and login details is saved to "User" with foreign key Reg_Id of table Registration.
this is my code:
DateTime dob = DateTime.Parse(txtDob.Text);
string formattedDate = dob.ToString("yyyy-MM-dd");
string qry = "insert into Registration(First_Name,Last_Name,Dob,Place,Zip,Phone_Number)values(#fname,#lname,#dob,#place,#zip,#phone);SELECT SCOPE_IDENTITY()";
MySqlCommand cmd = new MySqlCommand(qry, Connection.get());
cmd.Parameters.AddWithValue("#fname", txtFname.Text);
cmd.Parameters.AddWithValue("#lname", txtLname.Text);
cmd.Parameters.AddWithValue("#dob", formattedDate);
cmd.Parameters.AddWithValue("#place", txtPlace.Text);
cmd.Parameters.AddWithValue("#zip", txtZip.Text);
cmd.Parameters.AddWithValue("#phone", txtPhone.Text);
cmd.ExecuteNonQuery();
int modified = (int)cmd.ExecuteScalar();
Connection.close();
string qryToUser = "insert into User(User_Name,Password)values(#user,#password)";
MySqlCommand cmd1 = new MySqlCommand(qryToUser, Connection.get());
cmd.Parameters.AddWithValue("#user", txtUsername.Text);
cmd.Parameters.AddWithValue("#password", txtPasswordConfirm.Text);
cmd1.ExecuteNonQuery();
I am not able to get the REG_Id using cmd.ExecuteScalar() method.
Is there any other way or did i do anything wrong???
Please someone help me
You can just use LastInsertedId field :
cmd.ExecuteNonQuery();
long modified = cmd.LastInsertedId;
Looks like you have executed cmd.ExecuteNonQuery() before calling ExecuteScalar() method. I guess that the second call might fail and therefore not return an id.
Maybe you should check out a tutorial on how to use MySQL with C#

Inserting Data in an Access Database from Visual Studio using C#

when i try to inserting Data in an Acess Database from Visual stutio using C# i keep getting this Error "System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement."
protected void Button1_Click1(object sender, EventArgs e)
{
Guid newGUID = Guid.NewGuid();
OleDbConnection conn = new OleDbConnection(" Provider = Microsoft.ACE.OLEDB.12.0;" + "Data Source = " + Server.MapPath("App_Data/Group.accdb"));
OleDbCommand command = new OleDbCommand ("INSERT INTO [User] ( [Userid], [UserName], [Password], [Email], [Country], [CartID], [Address] ) VALUES (#Uname,#password,#email,#country,#address,#userid,#cartID)", conn);
conn.Open();
command.Parameters.AddWithValue("#userid", Convert.ToString(newGUID));
command.Parameters.AddWithValue("#Uname", username.Text);
command.Parameters.AddWithValue("#password", username.Text);
command.Parameters.AddWithValue("#email", email.Text);
command.Parameters.AddWithValue("#country", DropDownList1.SelectedItem.ToString());
command.Parameters.AddWithValue("#cartID", Convert.ToString(newGUID));
command.Parameters.AddWithValue("#address", address.Text);
command.ExecuteNonQuery();
conn.Close();
Response.Redirect("Login.aspx");
Response.Write("Registration is successful");
}
User is a reserved keyword. You need to enclose it between square brackets as you do for the fields
However your code has a more serious error.
Your parameters placeholders are not in the correct order in respect to the field names. So you need to fix the query and then remember that in
OleDb the parameters are not recognized by their name, but by their position.
Thus the code that add the parameters to collection should respect the order in which you want to retrieve the parameters value
OleDbCommand command = new OleDbCommand (#"INSERT INTO [User]
( [Userid], [UserName], [Password], [Email],
[Country], [CartID], [Address] ) VALUES
( #userid, #Uname, #password,#email,
#country,#cartID, #address)", conn);
conn.Open();
command.Parameters.AddWithValue("#userid", address.Text);
command.Parameters.AddWithValue("#Uname", username.Text);
command.Parameters.AddWithValue("#password", username.Text);
command.Parameters.AddWithValue("#email", email.Text);
command.Parameters.AddWithValue("#country",DropDownList1.SelectedItem.ToString());
command.Parameters.AddWithValue("#cartID", address.Text);
command.Parameters.AddWithValue("#address", address.Text);
command.ExecuteNonQuery();
By the way, you are passing the username textbox to both the Username field and UserID and Password. This seems unlikely (the same for the address textbox)
Finally it seems wrong also the use of a string to set the value of the fields cartID and UserID. The method AddWithValue has no way to know what is the DataType of the field that will be updated by the parameter. So it creates a parameter based on the datatype of the value. In your case the address.Text and username.Text are string, but if the database fields expects an integer bad things will happen.
If this is the case you should be certain that you have an integer and use
command.Parameters.AddWithValue("#userid", Convert.ToInt32(address.Text));
command.Parameters.AddWithValue("#cartID", Convert.ToInt32(address.Text));
In any case it is better use the correct Add method
command.Parameters.Add("#userid", OleDbType.Integer).Value = Convert.ToInt32(address.Text));

INSERT error ASP.NET

Hey I get an error saying there is something wrong with my code when inserting into a database, can't quite find it. The error suggests it is something in the INSERT statement, but appears on the line "cmd.ExecuteNonQuery();". I'm using an access database.
Error: Syntax error in INSERT INTO statement.
con.Open();
string mysql;
mysql = "INSERT INTO [User](FirstName,Surname,Age,HouseNumber,PostCode,Username,Password)
VALUES (?,?,?,?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbFirstName.Text);
cmd.Parameters.AddWithValue("#p2", tbSurname.Text);
cmd.Parameters.AddWithValue("#p3", int.Parse(tbAge.Text));
cmd.Parameters.AddWithValue("#p4", tbAddress1.Text);
cmd.Parameters.AddWithValue("#p5", tbPostCode.Text);
cmd.Parameters.AddWithValue("#p6", tbUsername.Text);
cmd.Parameters.AddWithValue("#p7", tbPassword.Text);
cmd.ExecuteNonQuery();
con.Close();
when you add parameters with value you need to convert it to matching type, if age is number then
cmd.Parameters.AddWithValue("#p3", int.Parse(tbAge.Text));
and also User is key word you can try with
"INSERT INTO [User] ([FirstName], [Surname], [Age], [HouseNumber], [PostCode], [Username], [Password]) VALUES (?,?,?,?,?,?,?)";
Have you tried replacing the ? with your parameters?
Correction: I believe you have to add OleDBParameters like so:
con.Open();
string mysql;
mysql = "INSERT INTO User(FirstName,Surname,Age,HouseNumber,PostCode,Username,Password)
VALUES (#p1,#p2,#p3,#p4,#p5,#p6,#p7)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#p1", tbFirstName.Text),
new OleDbParameter("#p2", tbSurname.Text),
...
});
cmd.ExecuteNonQuery();
con.Close();

Invalid column name error when Saving Selected Text From Drop Down Box into Database

Platform used : Microsoft Visual Studio 2010 (C#)
Database : SQL Server 2008 R2 Express
I want to get the text from the drop down and put it into database table. I am getting error saying
Invalid column name 'Type'.
though column is present in database table.
da.InsertCommand = new SqlCommand("insert into tblProductMaster ([Name],[Type],[Height],[Width],[Length],[Price]) values( #Name , #Type , #Height , #Width , #Length , #Price )", con);
da.InsertCommand.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
da.InsertCommand.Parameters.Add("#Type", SqlDbType.VarChar, 10).Value = ddlType.SelectedItem.ToString();
da.InsertCommand.Parameters.Add("#Height", SqlDbType.Float).Value = float.Parse(txtHeight.Text);
da.InsertCommand.Parameters.Add("#Width", SqlDbType.Float).Value = float.Parse(txtWidth.Text);
da.InsertCommand.Parameters.Add("#Length", SqlDbType.Float).Value = float.Parse(txtLength.Text);
da.InsertCommand.Parameters.Add("#Price", SqlDbType.SmallMoney).Value = int.Parse(txtPrice.Text);
da.InsertCommand.ExecuteNonQuery();
I believe your problem is that you are using a SQL Server reserved word ("Size") and you have not properly encapsulated it in your INSERT statement.
Try this:
da.InsertCommand = new SqlCommand("insert into tblProductMaster ([Name], [Size], [Height], [Width], [Length], [Price]) values(#Name, #Size, #Height, #Width, #Length, #Price)", con);
Notice the [ & ] around the column names... this will tell SQL Server to treat them as columns.
WARNING: I highly recommend you change these column names if you can. Using reserved words of any product is very poor database design and will continue to cause you problems and/or extra work. Better to fix it sooner than later.
#Sagar try this
string strCmd = #"insert into tblProductMaster ([Name], [Size], [Height], [Width], [Length], [Price]) values(#Name, #Size, #Height, #Width, #Length, #Price)";
Then
SqlCommand cmd = new SqlCommand(strCmd, con);
cmd.Parameters.Add("#Size", SqlDbType.VarChar, 10, ddlSize.SelectedItem.Value.ToString());
da.InsertCommand = cmd;

Categories