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)
Related
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.
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));
when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?
protected void btnAddBook_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (#Title, #Author, #Price, #Edition)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#Author", TextBox2.Text);
cmd.Parameters.AddWithValue("#Price", TextBox3.Text);
cmd.Parameters.AddWithValue("#Edition", TextBox4.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.
You could try to force the AddWithValue to create a numeric parameter with
cmd.Parameters.AddWithValue("#Price", Convert.ToDecimal(TextBox3.Text));
(Of course assuming a decimal Price column)
Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.
I have tried the following code to save to a database. The condition is are, I have a value in a dropdown list and the values are New= 1, and old=2. If the user selects 1 or new then it will save data to database or if they select old then it will show the exist data.
Now this time my label shows data inserted but the data is not saved to the table (But doesn't show any error).
protected void btnsave_Click(object sender, EventArgs e)
{
if (ddl.Text=="1")
{
cs.Open();
string query = "insert into resig (#id,#name,#email) values('"+txtgn.Text+"','"+txtgname.Text+"','"+txtsg.Text+"')";
SqlCommand cmd = new SqlCommand(query,cs);
lbdmsg.Text = "Data Inserted";
//txtgname.Text = ddl.SelectedItem.ToString();
}
else
{
cs.Open();
string query = "select name, email from resig where id='" + txtgn + "'";
SqlCommand cmd= new SqlCommand(query,cs);
dr =cmd.ExecuteReader();
while(dr.Read())
{
string name= txtgname.Text;
string email=txtsg.Text;
}
cs.Close();
}
}
I see 2 things;
You are try to parameterize your column names, not your values.
You are not executing your insert command with ExecuteNonQuery().
You should use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
if (ddl.Text == "1")
{
string query = "insert into resig (id,name,email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query,cs);
cmd.Parameters.AddWithValue("#id", txtgn.Text);
cmd.Parameters.AddWithValue("#name", txtgname.Text);
cmd.Parameters.AddWithValue("#email", txtsg.Text);
cs.Open();
cmd.ExecuteNonQuery();
}
Call cmd.ExecuteNonQuery() to run the command on your db
Your SQL is both wrong, and very dangerous/susceptible to SQL injection. The first list in parenthesis must be a column list, and the values list should be parameters to avoid SQL injection:
string query = "insert into resig (id, name, email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query, cs);
cmd.Parameters.Add(new SqlParameter("#id", txtgn.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtgname.Text));
cmd.Parameters.Add(new SqlParameter("#email", txtsg.Text));
cmd.ExecuteNonQuery();
You should parameterize the select statement as well. Why is this important? Consider the resulting SQL if the user entered this for id and selected old:
'; delete resig; --
Building SQL by concatenating user input opens your database to the whim of users with bad intentions, and in this day and age should never be used. Countless web sites have been defaced and had their data corrupted -- it was ill-considered back in the day, but now we know better, and there's no excuse.
I'm trying to switch come of my SQL queries to parameter queries but i keep getting some errors shown after the code below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (#Surname,[#Other Names],#mobileno,#date, #email, #faculty, #dept, [#Registration Number], #session,#thesis, #yearGrad, #tellerno, #amount, #address,#question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("#Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("#[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("#mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("#date", lblDate.Text);
cmd.Parameters.AddWithValue("#email", lblEmail.Text);
cmd.Parameters.AddWithValue("#faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("#dept", lblDept.Text);
cmd.Parameters.AddWithValue("#[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("#session", lblSession.Text);
cmd.Parameters.AddWithValue("#thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("#yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("#tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("#amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#address", lblAdd.Text);
cmd.Parameters.AddWithValue("#question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
Error message is:
Server Error in '/TranscriptReloaded' Application.
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#date".
"date" is a SQL reserved word, so the translation to SQL may be having a problem with it. Generally speaking you should avoid using the word date on its own as column names or as parameters.
Personally I would start by losing the #[two word] variable names (which you also use as [#two word] elsewhere). I don't know if this is the cause, but I have never seen this usage personally, and I'm dubious. Fine for column names (and table names), but variables? Not so sure. Changing the variable names is local to this code, so shouldn't cause any side-effects.