Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm having trouble with my code, I am getting a Invalid expression term ')' not sure what I'm doing wrong. Here is my code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source = '" + Server.MapPath("WSC_DB.mdb") + "'; Persist Security Info=False");
using (OleDbCommand cmd = new OleDbCommand("insert into Users(UserFirstName, UserLastName, ShipAddress, ShipCity, ShipState, UserPhone, UserEmail, UserName, UserPassword, LoginType) values (#FirstName, #LastName, #Address, #City, #State, #Zip, #Phone, #Email, #Username, #Password, #Logintype)", conn))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Parameters.AddWithValue("#State", DropDownList1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Zip", txtZip.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
cmd.Parameters.AddWithValue("#Logintype", "U");
conn.Open();
cmd.ExecuteNonQuery();
}
}
You have 10 items in your columns list and 11 items in your values list. The values list includes
... #City, #State, #Zip, #Phone, #Email, ...
but there is no Zip in the columns list
... ShipCity, ShipState, UserPhone, UserEmail, ...
I seem to remember to that you cannot use named parameters in SQL statement when using Jet OLEDB. You will need to replace #FirstName, #LastName, ... with a question mark '?'.
For better analysis of your error please include the entire error message and stack trace.
Related
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.
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);
";
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have this comamand and that error, in data i have zip code 79000 and table name site
private void Crt_clck_Click(object sender, EventArgs e)
{
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT CMC, [Site Name], [Phone Number], Zip_Code FROM site Where Zip_Code'" + Zipcode.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
can you help me with this
Change your sql statement to
cmd.CommandText = "SELECT CMC, [Site Name], [Phone Number], Zip_Code FROM site Where Zip_Code = '" + Zipcode.Text + "'";
You are missing the = which is needed for the syntax to be correct.
But you should think about using parameter instead to avoid SQL Injection.
Why do we always prefer using parameters in SQL statements? could be interesting for this, too.
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to insert data from my ASP.NET web application into a SQL Server database table (which I have previously created). The code I have doesn't seem to be working, the error message displays, and the actual data doesn't appear to get saved to the database.
var conn = new SqlConnection("Data Source=SHRIYA\\SQLEXPRESS;Initial Catalog=…;Integrated Security=True");
var insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password", conn);
insert.Parameters.AddWithValue("#GenerteID",lstuserID.SelectedIndex);
insert.Parameters.AddWithValue("#Name", txtname.Text);
insert.Parameters.AddWithValue("#Surname", txtsurname.Text);
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
insert.Parameters.AddWithValue("#Gender", ddlgender.SelectedItem);
insert.Parameters.AddWithValue("#Address", txtaddress.Text);
insert.Parameters.AddWithValue("#Postal_code", txtpostalcode.Text);
insert.Parameters.AddWithValue("#Phone_Number", txttele.Text);
insert.Parameters.AddWithValue("#Email", txtEmail.Text);
insert.Parameters.AddWithValue("#Password", txtpassword);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch (Exception)
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Error When Saving');", true);
}
conn.Close();
One error is to use txtpassword (i.e. a UI control as a whole) as a value for a SqlParameter. Replace it with txtpassword.Text (i.e. the textual value entered into the UI control):
insert.Parameters.AddWithValue("#Password", txtpassword.Text);
Your SQL command text is missing the closing parenthesis ) for VALUES (:
SqlCommand insert = new SqlCommand("Insert Into
tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,
Postal_code,Phone_Number,Email,Password)
values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,
#Postal_code,#Phone_Number,#Email,#Password)", conn);
// ^
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
That should be
insert.Parameters.AddWithValue("#ID_Number", txtid.Text);
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password", conn);
SQL syntax is wrong.
Missing ) at the last parameter #Password.
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(#GenerateID,#Name,#Surname,#ID_Number,#Gender,#Address,#Postal_code,#Phone_Number,#Email,#Password)", conn);