Syntax Error with INSERT statement. C# Access Database - c#

Trying to add a new record to a database. I have tried this type of code on a different project and it worked fine.
I keep getting a Syntax Error on INSERT statement:
I cannot seem to find the problem. I have searched for ages at other solutions that did not work. I have checked the table names a few times now and I can't see any inconsistencies.
Please note that I do have all the other remaining code to add the record, but didn't include it here.
Any help would be great. If anyone needs anymore information I will gladly comply.
I am working with C# and using Access Database.
void addRecord()
{
OleDbConnection myDatabaseConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=..\..\Database\TestionRetail.accdb;");
System.Data.OleDb.OleDbCommand command = new OleDbCommand();
command.Connection = myDatabaseConnection;
myDatabaseConnection.Open();
command.CommandText = "INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)" +
"VALUES (#PayrollNo, #Title, #FirstName, #Surname, #Position, #DOB, #Email, #PhoneNumber, #AlternateNumber, #AddressLine1, #AddressLine2, #City, #Postcode, #ContractType)";
command.Parameters.AddWithValue("#PayrollNo", txtPayroll.Text);
command.Parameters.AddWithValue("#Title", cmbTitle.SelectedIndex.ToString());
command.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
command.Parameters.AddWithValue("#Surname", txtSurname.Text);
command.Parameters.AddWithValue("#Position", txtPosition.Text);
command.Parameters.AddWithValue("#DOB", dtpDOB.Value.ToShortDateString());
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#PhoneNumber", txtPhoneNo.Text);
command.Parameters.AddWithValue("#AlternateNumber", txtAltPhoneNo.Text);
command.Parameters.AddWithValue("#AddressLine1", txtAddress1.Text);
command.Parameters.AddWithValue("#AddressLine2", txtAddress2.Text);
command.Parameters.AddWithValue("#City", txtTown.Text);
command.Parameters.AddWithValue("#Postcode", mtbPostcode.Text);
command.Parameters.AddWithValue("#ContractType", cmbContract.SelectedIndex.ToString());
try
{
command.ExecuteNonQuery();
var item = new NotifyIcon(this.components);
item.Visible = true;
item.Icon = System.Drawing.SystemIcons.Information;
item.ShowBalloonTip(2000, "Record Added", "Successfully added new record", ToolTipIcon.Info);
this.Hide();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
//5. Close the database
myDatabaseConnection.Close();
this.Hide();
}

Thanks for the help everyone, I fixed the problem by putting square brackets in

I believe you need a space after the closing parenthesis on the following line:
command.CommandText = "INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)" +
Otherwise your query will read:
INSERT INTO Employee (PayrollNo, Title, FirstName, Surname, Position, DOB, Email, PhoneNumber, AlternateNumber, AddressLine1, AddressLine2, City, Postcode, ContractType)VALUES (#PayrollNo, #Title, #FirstName, #Surname, #Position, #DOB, #Email, #PhoneNumber, #AlternateNumber, #AddressLine1, #AddressLine2, #City, #Postcode, #ContractType)
Which is why it is saying after INSERT because that's the first/last keyword it recognises before it encounters a syntax error.

A date field is not text. Thus:
command.Parameters.AddWithValue("#DOB", dtpDOB.Value);

Related

Error with SqlCommand and connection in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have errors with this code, but cannot find the problem. Please help.
SqlConnection myConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Software Project\BakeryProject Pages\BakeryProject\Databases\Users.mdf; Integrated Security = True");
myConnection.Open();
string commandText = "INSERT INTO Table (Id, Username, First_name, Last_Name, Password, Client, Staff, Admin )";
commandText += "VALUES (1, 'JohnSmith', 'John', 'Smith', 'Pass1', 'Client');";
SqlCommand myCommand = new SqlCommand(commandText, myConnection);
myCommand.Parameters.AddWithValue("#Id", mID);
myCommand.Parameters.AddWithValue("#Username", mUsername);
myCommand.Parameters.AddWithValue("#First_name", mNameFirst);
myCommand.Parameters.AddWithValue("#Last_name", mNameLast);
myCommand.Parameters.AddWithValue("#Password", mPassword);
myCommand.Parameters.AddWithValue("#Client", mClient);
myCommand.ExecuteNonQuery();
You are trying to add params, but you never defined any in your query. Perhaps this is what you meant:
string commandText = "INSERT INTO [Table] (Id, Username, First_name, Last_Name, Password, Client) ";
commandText += "VALUES (#Id, #Username, #First_name, #Last_name, #Password, #Client);";
SqlCommand myCommand = new SqlCommand(commandText, myConnection);
myCommand.Parameters.AddWithValue("#Id", mID);
myCommand.Parameters.AddWithValue("#Username", mUsername);
myCommand.Parameters.AddWithValue("#First_name", mNameFirst);
myCommand.Parameters.AddWithValue("#Last_name", mNameLast);
myCommand.Parameters.AddWithValue("#Password", mPassword);
myCommand.Parameters.AddWithValue("#Client", mClient);
myCommand.ExecuteNonQuery();
Note: I've also removed the Staff and Admin columns from your script as they don't have a param mentioned below. This should give you a point in the right direction though.
As a side-note, it's much easier to declare queries in C# by using a string literal. This way, you don't have to mess with the += and weird spacing issues that come from it:
string commandText =
#"
Insert [Table] (Id, Username, First_name, Last_Name, Password, Client)
Values (#Id, #Username, #First_name, #Last_name, #Password, #Client);
";

Syntax error in INSERT INTO statement ASP.Net C#

First of all, yes I know there are several other questions about this. I have reviewed and tried different solutions proposed in them; however I'm still getting a "Syntax error INSERT INTO statement" message when I click on the submit button to run the function.
I'm running VS 2015 and an Access 2010 db. The full error message is as follows:
Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO
statement. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
createAcc.btnCreateAccount_Click(Object sender, EventArgs e) in
e:\Documents\Visual Studio
2015\WebSites\OneStopFurniture\createAcc.aspx.cs:line 43
My code for the button handler is as follows:
protected void btnCreateAccount_Click(object sender, EventArgs e)
{
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=E:\\Documents\\Visual Studio 2015\\WebSites\\OneStopFurniture\\App_Data\\OneStopFur.accdb";
string InsertQuery;
try
{
connection.Open();
OleDbCommand cmdInsert = new OleDbCommand();
cmdInsert.Connection = connection;
InsertQuery= "INSERT INTO [userInfo] (
userName, password, firstName, lastName, userAddress, userCity, userZip, userPhone, userEmail
) VALUES (
#userName, #password, #firstName, #lastName, #userAddress, #userCity, #userState, #userZip, #userPhone, #userEmail
)";
cmdInsert.Parameters.AddWithValue("#userName", txtUserName.Text);
cmdInsert.Parameters.AddWithValue("#password", txtPassword.Text);
cmdInsert.Parameters.AddWithValue("#firstName", txtFirstName.Text);
cmdInsert.Parameters.AddWithValue("#lastName", txtLastName.Text);
cmdInsert.Parameters.AddWithValue("#userAddress", txtAddress.Text);
cmdInsert.Parameters.AddWithValue("#userCity", txtCity.Text);
cmdInsert.Parameters.AddWithValue("#userState", txtState.Text);
cmdInsert.Parameters.AddWithValue("#userZip", txtZip.Text);
cmdInsert.Parameters.AddWithValue("#userPhone", txtPhone.Text);
cmdInsert.Parameters.AddWithValue("#userEmail", txtEmail.Text);
cmdInsert.CommandText = InsertQuery;
cmdInsert.ExecuteNonQuery();
lblConfirm.Visible = true;
lblConfirm.Text = "Account creation successful.";
}
catch (Exception ex)
{
lblConfirm.Visible = true;
lblConfirm.Text = "Unable to create" + ex;
}
}
Can someone please tell me what I am overlooking here? At this point, I'm at a complete lose.
Thanks.
Missing UserState in column list.
InsertQuery= "INSERT INTO [userInfo]
([userName], [password], [firstName], [lastName], [userAddress], [userCity], [userState], [userZip], [userPhone], [userEmail])
VALUES(#userName, #password, #firstName, #lastName, #userAddress, #userCity, #userState, #userZip, #userPhone, #userEmail)";
The good practise is to qoute everything to avoid collision with keywords.
The immediate error is caused by the word Password. This is a reserved keyword in MS-Access. Use square brackets around it.
InsertQuery= #"INSERT INTO [userInfo](userName, [password], firstName,
lastName, userAddress, userCity, userState, userZip,
userPhone, userEmail)
VALUES(#userName, #password, #firstName,
#lastName, #userAddress, #userCity, #userState, #userZip,
#userPhone, #userEmail)";
After fixing this error you need also to add the column UserState (or whatever is called) because you have added a parameter for it.
Keep in mind that in OleDb the parameters are positional. This means the the first field receives the value from the first parameter, whatever name you have used, so missing a field or inverting the position of a parameter in the collection could cause bugs very difficult to spot. Double your checks here.

Insert statement into SQL Server db

I'm developing an ASP.NET MVC Web Application using SQL Server.
I am trying to INSERT a new entry into my database and I don't understand what am I doing wrong.
I get an exception on the line:
command.ExecuteNonQuery();
The code is:
try
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=UniversityManager;Integrated Security=True");
using (connection)
{
//SqlCommand command = new SqlCommand(
// "INSERT INTO Students VALUES(#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp);",
// connection);
connection.Open();
String sql = "INSERT INTO Students(Id,Name,Surname,Year,PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#Id", SqlDbType.Int);
command.Parameters["#Id"].Value = 5;
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = collection.Name;
command.Parameters.Add("#Surname", SqlDbType.VarChar);
command.Parameters["#Surname"].Value = collection.Surname;
command.Parameters.Add("#Year", SqlDbType.Int);
command.Parameters["#Year"].Value = collection.Year;
command.Parameters.Add("#PhoneNumber", SqlDbType.VarChar);
command.Parameters["#PhoneNumber"].Value = collection.PhoneNumber;
command.Parameters.Add("#Cnp", SqlDbType.VarChar);
command.Parameters["#Cnp"].Value = collection.Cnp;
command.ExecuteNonQuery();
connection.Close();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Thank you!
YEAR is a reserved keyword for Sql Server. So, if you really have a column with that name, then you need to enclose it in square brackets every time you refer to it. Better change that name
String sql = "INSERT INTO Students(Id,Name,Surname,[Year],PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
Another possibility is the Id column. If this column has the IDENTITY property set to true, then you should not set a value for it. It is automatically calculated by the database engine.
Looking at your innerexception message, it seems the problem is due to one or more of your parameters contains more text than allowed by the database field size.
You could try something like this (for each varchar parameter)
// Assuming the Name field is defined as varchar(15)
command.Parameters.Add("#Name", SqlDbType.VarChar, 15);
command.Parameters["#Name"].Value = collection.Name;
The String or binary data would be truncated exception means you're trying to insert a value that is too large for one of the columns in your Student table. For example, your Name field has a maximum length of 10 but you're trying to insert a 15 character name.
Check the values you're inserting and see if they're too large for the columns.

Oledb Overflow error in ASP.NET 3.5 C# Website

I am getting a strange "Overflow" error while inserting data to my access database. Actually it works fine locally, but not on the server so I think it can be an OS specific error as my local system is a 64-bit Windows 7 but cant say about the server. But even if it is an OS specific problem, it should have broke up with a numeric value being inserted but the data columns in my database are all text, memo and datetime and an auto-number field.
Here is the code:
string cmdd = #"Insert into Alumni_tb (A_Name, Batch, Stream, Adm_No, Email, Address, Profession, Contact_No, Comments, Date_Added, Last_Update_Date, Active)
values (#A_Name,#Batch, #Stream, #Adm_No, #Email, #Address, #Profession,#Contact_No, #Comments, #Date_Added, #Last_Update_Date , #isActive)";
OleDbCommand cmd = new OleDbCommand(cmdd, conn);
cmd.Parameters.AddWithValue("#A_Name", aName);
cmd.Parameters.AddWithValue("#Batch", Batch);
cmd.Parameters.AddWithValue("#Adm_No", admno);
cmd.Parameters.AddWithValue("#Stream", stream);
cmd.Parameters.AddWithValue("#Email", Email);
cmd.Parameters.AddWithValue("#Address", address);
cmd.Parameters.AddWithValue("#Profession", prof);
cmd.Parameters.AddWithValue("#Contact_No", contno);
cmd.Parameters.AddWithValue("#Comments", comments);
cmd.Parameters.AddWithValue("#Date_Added", dateAdded);
cmd.Parameters.AddWithValue("#Last_Update_Date", lastUpdateDate);
cmd.Parameters.AddWithValue("#isActive", true);
conn.Open();
int cnt = 0;
cnt=cmd.ExecuteNonQuery();
if (cnt > 0)
{
//Display Ok Message
return;
}
else
{
//Display Error Message
}
The variable passing values to the params are all string and have been initalized and populated before defining the insert query.
In the database, the columns and datatype are described below.
A_Name is a Text;
Batch is Text;
Stream is Text;
Adm_No is Text;
Email is Text;
Address is Memo;
Profession is Text;
Contact_no is Text;
Comments is Memo;
Date_added is DateTime;
Last_update_date is DateTime;
Active is Yes/No;
I only get an "Overflow" error message, at cmd.ExecuteNonQuery();Please help!!!
I think you should use SqlCommand..
SqlCommand cmd = new SqlCommand(string cmdd = #"Insert into Alumni_tb (A_Name, Batch, Stream, Adm_No, Email, Address, Profession, Contact_No, Comments, Date_Added, Last_Update_Date, Active) values (#A_Name,#Batch, #Stream, #Adm_No, #Email, #Address, #Profession,#Contact_No, #Comments, #Date_Added, #Last_Update_Date , #isActive)
I did not see you used OleDbCommand, sorry..

Try/Catch method error ASP.NET

I'm trying to make this work. I want it to check if a record exist after inserting but it always return an error: Line 1: Incorrect syntax near 'nvarchar'. Can someone point out to me whats wrong in my declaration? Also if you have a better try catch method please enlighten me more. Just new to programming in ASP.NET
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
string connString_LibrarySystem = "Server=DEVSERVER;User ID=sa;Password=Sup3r-Us3r;Database=LibrarySystem";
string strSQL = "INSERT INTO TblBooks (bookid, booktitle, lastname, firstname, description, categoryid, dateadded, statusid, quantity, isdeleted) VALUES (#bookid, #booktitle, #lastname, #firstname, #description, #categoryid, #dateadded, #statusid, #quantity, #isdeleted)";
SqlConnection conn = new SqlConnection(connString_LibrarySystem);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand(strSQL, conn);
cmd.Parameters.AddWithValue("#bookid", Request.Form["bookid"]);
cmd.Parameters.AddWithValue("#booktitle", Request.Form["booktitle"]);
cmd.Parameters.AddWithValue("#lastname", Request.Form["lastname"]);
cmd.Parameters.AddWithValue("#firstname", Request.Form["firstname"]);
cmd.Parameters.AddWithValue("#description", Request.Form["description"]);
cmd.Parameters.AddWithValue("#categoryid", Request.Form["categoryid"]);
cmd.Parameters.AddWithValue("#dateadded", Request.Form["dateadded"]);
cmd.Parameters.AddWithValue("#statusid", Request.Form["statusid"]);
cmd.Parameters.AddWithValue("#quantity", Request.Form["quantity"]);
cmd.Parameters.AddWithValue("#isdeleted", Request.Form["isdeleted"]);
cmd.ExecuteNonQuery();
{
conn.Close();
}
statuslabel.Text = "Insert successful";
}
EDIT: There just removed the datatypes.
You don't have to include data type in insert statements. Skip them.
Try
string strSQL = "INSERT INTO TblBooks (bookid, booktitle, lastname, firstname, description, categoryid, dateadded, statusid, quantity, isdeleted) VALUES (#bookid, #booktitle , #lastname, #firstname, #description, #categoryid, #dateadded , #statusid , #quantity, #isdeleted)";
don't put the types in your values.
string strSQL = "INSERT INTO TblBooks (bookid, booktitle, lastname, firstname, description, categoryid, dateadded, statusid, quantity, isdeleted) VALUES (#bookid , #booktitle , #lastname , #firstname , #description , #categoryid , #dateadded , #statusid , #quantity , #isdeleted )";
In order to make this work you need to remove the datatypes from the sqlstring variable.
I would probably switch to using a stored procedure and then load parameters since that's basically what you're doing here with the addwithvalue command
also cmd.ExecuteNonQuery() will return an int to tell you that it's been added successfully. if it returns a 1 you know that's it's complete.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
At first, remove your types in the SQL, you do not need them (As other answers suggested)
Second, you add a parameter to the query by this :
cmd.Parameters.AddWithValue("#bookid", Request.Form["bookid"]);
You do not make sure that Request.Form["bookid"] is not null, this will cause your current problem
Get rid of the data types in the values list. You don't need them.

Categories

Resources