Syntax error in INSERT INTO statement ASP.Net C# - 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.

Related

Data type mismatch won't let me save to database

I'm writing a lab for a C# class to manage an Access database. It's a C# GUI program that uses a DataGridView to view a database and write to it.
The save table class will not work and gives me the same exception: SystemData.OleDb.OleDbException: 'Data type mismatch in criteria expression.'
I understand the code might be vulnerable to SQL injection but this is a one time lab that's on the clock, need to get a solution to the problem at hand. Not worried about parameters unless they'd fix this issue.
private void button2_Click_1(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/sdepasqu/Documents/Customer Database.accdb";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (OleDbConnection conn = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand(#"INSERT INTO customer([CUST_ID], [FIRST_NAME], [LAST_NAME], [ADDRESS], [CITY], [STATE], [POSTAL], [EMAIL], [BALANCE], [CREDIT_LIMIT], [REP_ID]) VALUES(#cust_id, #first_name, #last_name, #address, #city, #state, #postal, #email, #balance, #credit_limit, #rep_id)", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#id", row.Cells["iDDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#cust_id", row.Cells["cUSTIDDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#first_name", row.Cells["fIRSTNAMEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#last_name", row.Cells["lASTNAMEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#address", row.Cells["aDDRESSDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#city", row.Cells["cITYDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#state", row.Cells["sTATEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#postal", row.Cells["pOSTALDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("email", row.Cells["eMAILDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#balance", row.Cells["bALANCEDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#credit_limit", row.Cells["cREDITLIMITDataGridViewTextBoxColumn"].Value);
cmd.Parameters.AddWithValue("#rep_id", row.Cells["rEPIDDataGridViewTextBoxColumn"].Value);
cmd.ExecuteNonQuery();
}
}
}
}
The database table in question:
Tried to do a cmd.Parameters.Add and specify the OleDbDataType but it threw up a bunch of errors at me.
Here is an example of cmd parameter:
cmd.Parameters.Add("#item_number", SqlDbType.VarChar).Value = lblitemnum.Text;
Go through your table and write down what type each column is , and re-write your code compared to example above. AutoNumber will probably be int, shorttext should be varchar, cust_id should be int also. Currency should be money, an so on.

Attempting to INSERT values into a MySQL DB from C# code within a form, but getting "Column cannot be NULL

All - thanks in advance for your time. So, background info - I am trying to create a form for contact registration using C# to pass the information into my MySql DB. If I use the query directly in the code, it works. However, I have read that you should use a stored procedure for security. So, working code is:
using (MySqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"INSERT INTO Contacts (contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell) VALUES (#ciD,#ln, #fn, #add, #city, #state, #zip, #email, #news, #cell)";
//cmd.CommandText = "insert_contact";
//cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#cID", MySqlDbType.VarChar);
cmd.Parameters.Add("#ln", MySqlDbType.VarChar);
cmd.Parameters.Add("#fn", MySqlDbType.VarChar);
cmd.Parameters.Add("#add", MySqlDbType.VarChar);
cmd.Parameters.Add("#city", MySqlDbType.VarChar);
cmd.Parameters.Add("#state", MySqlDbType.VarChar);
cmd.Parameters.Add("#zip", MySqlDbType.VarChar);
cmd.Parameters.Add("#email", MySqlDbType.VarChar);
cmd.Parameters.Add("#news", MySqlDbType.Bit);
cmd.Parameters.Add("#cell", MySqlDbType.Bit);
cmd.Parameters["#cID"].Value = default;
cmd.Parameters["#ln"].Value = lastName_TextBox.Text;
cmd.Parameters["#fn"].Value = firstName_TextBox.Text;
cmd.Parameters["#add"].Value = address_TextBox.Text;
cmd.Parameters["#city"].Value = city_TextBox.Text;
cmd.Parameters["#state"].Value = state_DropDown.Text;
cmd.Parameters["#zip"].Value = zipCode_TextBox.Text;
cmd.Parameters["#email"].Value = email_TextBox.Text;
cmd.Parameters["#news"].Value = newsletter_CheckBox.Checked;
cmd.Parameters["#cell"].Value = cell_CheckBox.Checked;
cmd.ExecuteNonQuery();
conn.Close();
However, when I change the following lines to this, I get the "cannot be NULL error":
conn.Open();
//cmd.CommandText = #"INSERT INTO Contacts (contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell) VALUES (#ciD,#ln, #fn, #add, #city, #state, #zip, #email, #news, #cell)";
cmd.CommandText = "insert_contact";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
My stored procedure on the DB is (I suspect this is where the error may be):
BEGIN
INSERT INTO Contacts (contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell)
VALUES (#ciD,#ln, #fn, #add, #city, #state, #zip, #email, #news, #cell);
END
I have attempted the following, with the accompanying errors:
• Changed the "#" in the stored procedures to a "?" -(Get an error in SQL Syntax)
• Changing all of the columns to accept a NULL value. -(All columns then have a NULL value).
My apologies if this is something easy - just starting out learning.
Thanks in advance!
Pherix
Your insert_contact stored procedure have to provide the parameters (with the type) as below:
CREATE PROCEDURE insert_contact
(
IN cID VARCHAR,
IN ln VARCHAR(30),
IN fn VARCHAR(45),
IN `add` VARCHAR(30),
IN city VARCHAR(30),
IN state VARCHAR(10),
IN zip VARCHAR(20),
IN email VARCHAR(45),
IN news bit,
IN cell bit,
)
BEGIN
INSERT INTO Contacts
(contactID,last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell)
VALUES
(#cID, #ln, #fn, #add, #city, #state, #zip, #email, #news, #cell);
END
And in case there is any parameter which conflict with MySQL reserved words, you need to escape the reserved words with single quotes.
Note:
Your contactID column was int(11) type but you provide the cID parameter as VARCHAR type. You need to take concern that the column type was unmatched and possible lead an exception.
Reference
MySQL - Working with Stored Procedures
Ok, finally found what the Stored Procedure liked:
BEGIN
INSERT INTO Contacts
(last_name,first_name,address,city,state,zip_code,email_address,newsletter,is_Cell)
VALUES
(ln, fn, address, city, state, zip, email, news, cell);
END
Apparently, it did not like the "#" in front of the passed values.

Trying to insert data to database in c# forms but getting this error message when insert button is hit. Parameter not supplied

Connecting my program to the database but running into this problem.
Error message:
The parameterized query '#first_name nvarchar(1), #last_name nvarchar(1), #email nvarchar(' expects the parameter '#username', which is not supplied.
Absolutely lost not really sure what the error message is saying.
Here's my code to insert the data into SQL Server database tables. Any advice is appreciated.
public bool Insert(userBLL u)
{
bool Success = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
String sql = "INSERT INTO tbl_users (first_name, last_name, email, username, password, contact, address, gender, user_type, added_date, added_by) VALUES (#first_name, #last_name, #email, #username, #password, #contact, #address, #gender, #user_type, #added_date, #added_by)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#first_name", u.first_name);
cmd.Parameters.AddWithValue("#last_name", u.last_name);
cmd.Parameters.AddWithValue("#email", u.email);
cmd.Parameters.AddWithValue("#username", u.username);
cmd.Parameters.AddWithValue("#password", u.password);
cmd.Parameters.AddWithValue("#contact", u.contact);
cmd.Parameters.AddWithValue("#address", u.address);
cmd.Parameters.AddWithValue("#gender", u.gender);
cmd.Parameters.AddWithValue("#user_type", u.user_type);
cmd.Parameters.AddWithValue("#added_date", u.added_date);
cmd.Parameters.AddWithValue("#added_by", u.added_by);
conn.Open();
int rows = cmd.ExecuteNonQuery();
// value of rows will be greater than 0 or else
if (rows > 0)
{
Success = true;
}
else
{
Success = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return Success;
}
After observing your code, In region(#region Insert data to database) that you shared, I think there was no problem in your code.
Make sure userBLL object is not null that you passed in function Insert. So debug your code one more time.
By observing your code the only reason for this error looks like the userbill object has null value for username . So debug it one time and then share

Syntax Error with INSERT statement. C# Access Database

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

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