Inserting Data in an Access Database from Visual Studio using C# - 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));

Related

Unhandled exception occurs when Clicking Save Button

private void btnSave_Click(object sender, EventArgs e)
{
if (!ValidInput())
return;
using (var conn = new OleDbConnection(DatabaseObjects.ConnectionString))
{
conn.Open();
command = new OleDbCommand("insert into Students (RollNo, SName, FName, DOB, Class, Section) values (#RollNo, #SName, #FName, #DOB, #Class, #Section)", conn);
command.Parameters.Add(new OleDbParameter("RollNo", txtRollNo.Text));
command.Parameters.Add(new OleDbParameter("SName", txtSName.Text));
command.Parameters.Add(new OleDbParameter("FName", txtFName.Text));
command.Parameters.Add(new OleDbParameter("DOB", dtpDOB.Text));
command.Parameters.Add(new OleDbParameter("Class", cmbClass.Text));
command.Parameters.Add(new OleDbParameter("Section", cmbSection.Text));
command.ExecuteNonQuery();
MessageBox.Show("Saved");
}
}
When I Click Save Button this error is rising (Insert Into Syntax Error).
I have troubleshooted the code, I Find that if Field Section and Parameter #Section is removed from insert statement. Then Code works fine. But I want to Get ComboBox(CmbSection) Value of it and also to store on Database. How Can I?
"Section" is a reserved word in MS Access, so its use here is confusing the query parser.
You can explicitly tell the query what identifiers are referring to database objects (columns, tables, etc.) by wrapping them in square brackets:
INSERT INTO [Students]
([RollNo], [SName], [FName], [DOB], [Class], [Section])
VALUES (#RollNo, #SName, #FName, #DOB, #Class, #Section)

Get the recent ID and insert it to another table in ASP.NET

Please help - I'm creating a simple register from I'm trying to get the userID and insert the UserID from User table into the Employee table. I get an error at the line
newID = (int)cmd.ExecuteScalar();
My User table has a primary key UserID, the Employee table has a column UserID as foreign key.
Thank you in advance!
Here is my register.cs
// instantiate
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
int newID;
string query = #"INSERT INTO Users VALUES (#TypeID, #EmployeeId, #Username, #Password, #SecurityQuestion1, #SecurityAnswer1, #SecurityQuestion2, #SecurityAnswer2, #DateModified);SELECT CAST(scope_identity() AS int";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TypeID", ddlUserTypes.SelectedValue);
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", Helper.CreateSHAHash(txtPW.Text));
cmd.Parameters.AddWithValue("#SecurityQuestion1", ddlSec1.SelectedValue);
cmd.Parameters.AddWithValue("#SecurityAnswer1", txtSecAns1.Text);
cmd.Parameters.AddWithValue("#SecurityQuestion2", ddlSec2.SelectedValue);
cmd.Parameters.AddWithValue("#SecurityAnswer2", txtSecAns2.Text);
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
newID = (int)cmd.ExecuteScalar();
con.Close();
}
string query2 = #"INSERT INTO Employees VALUES (#FirstName, #MiddleName, #LastName, #EmployeeNumber, #Gender, #Birthdate, #Birthplace, #Nationality, #CivilStatus, #PermamentAddress, #PresentAddress, #ContactNumber, #Email, #Position, #Department, #Designation, #DateHired, #EmploymentStatus, #TIN, #SSS, #HDMF, #PHIC, #Supervisor, #Remarks, #Photo, #Attachments, #DateModified)";
using (SqlCommand cmd = new SqlCommand(query2, con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFN.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMD.Text);
cmd.Parameters.AddWithValue("#LastName", txtLN.Text);
cmd.Parameters.AddWithValue("#EmployeeNumber", txtEmpNo.Text);
cmd.Parameters.AddWithValue("#Gender", ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("#Birthdate", txtbdate.Text);
cmd.Parameters.AddWithValue("#Birthplace", txtBP.Text);
cmd.Parameters.AddWithValue("#Nationality", txtNat.Text);
cmd.Parameters.AddWithValue("#CivilStatus", ddlCIv.SelectedValue);
cmd.Parameters.AddWithValue("#PermamentAddress", txtPermAdd.Text);
cmd.Parameters.AddWithValue("#PresentAddress", txtPreAdd.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContactNo.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Position", txtPosi.Text);
cmd.Parameters.AddWithValue("#Department", txtDept.Text);
cmd.Parameters.AddWithValue("#Designation", txtDesig.Text);
cmd.Parameters.AddWithValue("#DateHired", txtdateh.Text);
cmd.Parameters.AddWithValue("#EmploymentStatus", txtEmpl.Text);
cmd.Parameters.AddWithValue("#TIN", txtTin.Text);
cmd.Parameters.AddWithValue("#SSS", txtSSS.Text);
cmd.Parameters.AddWithValue("#HDMF", txtPhilH.Text);
cmd.Parameters.AddWithValue("#PHIC", txtPag.Text);
cmd.Parameters.AddWithValue("#Supervisor", txtSuper.Text);
cmd.Parameters.AddWithValue("#Remarks", txtRemarks.Text);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss-") + fuImage.FileName;
cmd.Parameters.AddWithValue("#Photo", fileName);
fuImage.SaveAs(Server.MapPath("~/EmployeeData/Images/" + fileName));
string attachments = DateTime.Now.ToString("yyyyMMddHHmmss-") + fuAttach.FileName;
cmd.Parameters.AddWithValue("#Attachments", attachments);
fuAttach.SaveAs(Server.MapPath("~/EmployeeData/Attachments/" + attachments));
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
I'm not sure how this code gets an error at the line you're saying it happens, since I'd expect an error.at the line before the one mentioned. Here are a variety of tips, too long for a comment. I hope they sort out the problem, and if they dont, then the first point will help you get to the answer.
When asking for help about an error, please post the error that you got. This is the most important thing about diagnosing an error.
The line before the error is cmd.ExecuteNonQuery(), which will execute the command, inserting the record. Then you do cmd.ExecuteScalar(), which will execute the command again, inserting another record. Remove the cmd.ExecuteNonQuery(), since you need the identity value back from ExecuteScalar.
I'm not sure how the cmd.ExecuteNonQuery() works (it must do, unless you are mistaken in telling us that it crashes on the next line), since there is a typo in the query, missing the close bracket from the end SELECT CAST(scope_identity() AS int.
Please Can we stop using AddWithValue.
There's no need to Close the connection (ever), since it's in a using block. When it exits that block, the implicit Dispose will call Close.
Consider adding a Transaction. You are doing two separate inserts. If the second one fails, you will be left with the first record in the database. If you use a transaction around both commands, then either they both get in, or neither get in.
You're passing #DateModified the value DateTime.Now, which is a 'Local' time (look at the Kind property). When you read the value back from SQL, unless you call SpecifyKind, it won't be a local time, leading to discrepancies. Safer to always store and read the value as UTC (by using DateTime.UtcNow here, and SpecifyKind UTC when you read it) or switch to using DateTimeOffset.

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#

How to insert primary key in database?

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)

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

Categories