Strange behaviour on Update query with C# and Access - c#

I am facing a strange problem, When i try to run the below code to update a record in access db.
string updateQuery = "UPDATE Employee SET Employee_name = #name, Employee_desig = #designation, Employee_salary = #salary, Employee_phone = #phone, Employee_mobile = #mobile, Employee_email = #email, Employee_status = #status WHERE (((Employee_id)=#empId));";
dbCmd.CommandText = updateQuery;
dbCmd.Parameters.AddWithValue("#designation", designation);
dbCmd.Parameters.AddWithValue("#email", email);
dbCmd.Parameters.AddWithValue("#mobile", mobile);
dbCmd.Parameters.AddWithValue("#name", name);
dbCmd.Parameters.AddWithValue("#phone", phone);
dbCmd.Parameters.AddWithValue("#salary", salary);
dbCmd.Parameters.AddWithValue("#status", status);
dbCmd.Parameters.AddWithValue("#empId", employeeId);
dbCmd.ExecuteNonQuery();
ExecuteNonQuery() return 1. But when i check in db, inputs are updated in different columns.
input values are
designation="Manager"
email="e"
mobile="2"
name="n"
phone="1"
salary=10.0
status="Active"
employeeId=3
any help will be appreciated.

In the context of ACE OLEDB the parameter names are ignored and the parameters must be defined in the same order that they appear in the SQL statement.

Related

Getting a "System.Data.SQLite.SQLiteException: SQL logic error" while trying to add rows to my database with SQLite C#

So I'm trying to insert a new row into my database with SQLite3, and for some reason I'm getting a SQL logic error.
Database dbObject = new Database();
string query = "INSERT INTO info ('firstName, lastName, email') VALUES (#firstName, #lastName, #email";
SQLiteCommand myCommand = new SQLiteCommand(query, dbObject.Connection); //Opens chain of commands
dbObject.OpenConnection();
myCommand.Parameters.AddWithValue("#firsName", "blank name");
myCommand.Parameters.AddWithValue("#lastName", "blank last name");
myCommand.Parameters.AddWithValue("#email", "blank#gmail.com");
var result = myCommand.ExecuteNonQuery();
dbObject.CloseConnection();
Console.WriteLine("Rows added: {0}", result);
Console.ReadKey();
Can someone please tell me what am I doing wrong? Thank you!
Your query misses bracket at the end (after #email).
Moreover, I am not sure about the single quotes you added between firstName and email. I think they should be removed.
"INSERT INTO info (firstName, lastName, email) VALUES (#firstName, #lastName, #email)";
And as a side note that is not relevant to the error, you also need to dispose SQLiteCommand class as it is not disposed by itself. You can do it with using statement.

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.

Why I'm getting Incorrect syntax near ')' error?

I'm trying to create a registration page using C# on Visual Basic 2012. When I debug I get 0 errors, but when I try to register an account I get the following error.
"Incorrect syntax near ')'"
If I try to create an account with an existing username it says that username already exist. So I'm able to connect to the SQL server, but I'm not sure where I went wrong.
This registration page should create accounts in my DB DNMembership> Table> Accounts
Here is my code I'm working with.
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString);
con.Open();
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#AccountName", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Passphrase", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
What did I do wrong?
Looks like you forget to add VALUES part in your INSERT command.
VALUES
Introduces the list or lists of data values to be inserted. There must
be one data value for each column in column_list, if specified, or in
the table. The value list must be enclosed in parentheses.
Change your sql query like;
string insCmd = #"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES(#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)";
And use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegDNMembershipConnectionString"].ConnectionString))
{
using(SqlCommand insertUser = new...)
{
//Your code..
}
}
You haven't specified any parameters in your SQL, or a VALUES section - you're saying "I want to insert into these fields..." but not what you want to insert. It should be something like:
string insCmd =
"Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) "
+ "Values (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country");
You need to change the SQL statement:
string insCmd = "Insert into Accounts (AccountName, Passphrase, EmailAddress, FullName, Country) VALUES (#AccountName,#Passphrase,#EmailAddress,#FullName,#Country)";
You are missing part of Insert statement
INSERT INTO table (col1, col2) VALUES (#col1, #col2)
Or if you want to insert all values into columns in order they are in table
INSERT INTO table VALUES (#col1, #col2)
There is several alternatives for INSERT command in SQL Server.
Specify COLUMNS and after that specify VALUES
SQL Syntax - INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE(AccountName, Passphrase, EmailAddress, FullName, Country)
VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
If you are sure about the order of columns you can skip specifying columns, this can be risky in case you screw up order of VALUES you will insert values into wrong columns
SQL Sytanx - INSERT INTO TABLE VALUES ('AccountName', 'Passphrase', 'EmailAddress', 'FullName', 'Country')
C# string insCmd = "INSERT INTO TABLE VALUES (#AccountName, #Passphrase, #EmailAddress, #FullName, #Country)"
Good resources to read would be
W3School - http://www.w3schools.com/sql/sql_insert.asp
Technet - http://technet.microsoft.com/en-us/library/dd776381(v=sql.105).aspx
Alternative to INSERT INTO TABLE you can call stored procedures from C# that inserts into table. Use of stored procedures can help you reduce ad-hoc queries, help prevent SQL injection, reduce network traffic, add additional validation server side. Your code will look as follows.
SqlCommand cmd = new SqlCommand("usp_InsertIntoAccount", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#AccountName", TextBoxUN.Text));
cmd.Parameters.Add(new SqlParameter("#Passphrase", TextBoxPass.Text));
cmd.Parameters.Add(new SqlParameter("#EmailAddress", TextBoxEA.Text));
cmd.Parameters.Add(new SqlParameter("#FullName", TextBoxFN.Text));
cmd.Parameters.Add(new SqlParameter("#Country", DropDownListCountry.SelectedItem.ToString()));
try
{
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch(Exception er)
{
Response.Write("<b>Something Really Bad Happened... Please Try Again.< /br></b>");
Response.Write(er.Message);
}
Additional resources are listed on answer at the following questions How to execute a stored procedure within C# program

Cannot update id - id not updatable

I try to update my info data (in access database) on employee table, but I get this error that says cannot update id - id not updatable
Lets say I have this employee
ID : 1
Name : Mark
LastName : Jonhson
Age : 33
I write update statement, in case I want to change his info in future, ...let's say
ID : 1
Name : Mark
LastName : Markson
Age: 34
My code What did I do wrong and how do I update/edit my data
private void button2_Click_2(object sender, EventArgs e)
{
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "Update Employee set ID = #ID, Name = #Name, LastName = #LastName, User_name = #User_name, Password = #Password, E_mail = #E_mail, Address = #Address";
cmd.Parameters.Add("#ID", ID.Text);
cmd.Parameters.Add("#Name", name.Text);
cmd.Parameters.Add("#LastName", lastName.Text);
cmd.Parameters.Add("#User_name", userName.Text);
cmd.Parameters.Add("#Password", pass.Text);
cmd.Parameters.Add("#E_mail", eMail.Text);
cmd.Parameters.Add("#Address", address.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("User updated!");
myConncetion.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You should add a WHERE to your command text.If you don't it,all of your records will be change.I think you want this:
cmd.CommandText = "Update Employee SET Name = #Name, LastName = #LastName, User_name = #User_name, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #ID";
I suppose that your "ID" is not just a piece of data, but the table primary key too. In that case you should never update that.
The primary key is meant to be immutable, not only because it uniquely identifies a record in the DB, also all other tables will reference this column though foreign keys, which will either break or leave orphaned rows everywhere. Additionally, what's the purpose of updating it? The user is not even aware of its existence, since it's only part of the internal DB structure that keeps integrity, nothing more.
In short, don't try it.
If you really want to update it, the column should not be autogenerated, as the DB engine most likely will catch your error and prevent it.
Chances are, ID is an auto-generated primary key in the database. You cannot update that.
Actually, your UPDATE statement would update all records in the table, since it is lacking a WHERE clause. This is very dangerous. You should specify the record you want to update in your WHERE clause, and when possible, reference it via the primary key:
UPDATE Employee Name = #Name, LastName = #LastName, User_name = #User_name, Password = #Password, E_mail = #E_mail, Address = #Address
WHERE Id = #Id;

ASP.NET ODBC Query with parameters

Please help me, I don't know what can be wrong with the following code:
OdbcConnection conn = new OdbcConnection(connString);
String query = "INSERT INTO customer (custId, custName, custPass, "+
"custEmail, custAddress, custAge) VALUES (" +
"#ID, #Name, #Pass, #Email, #Address, #Age)";
OdbcCommand exe = new OdbcCommand(query, conn);
exe.Parameters.Add("#ID", OdbcType.UniqueIdentifier).Value = id;
exe.Parameters.Add("#Name", OdbcType.VarChar).Value = name;
exe.Parameters.Add("#Pass", OdbcType.VarChar).Value = pass;
exe.Parameters.Add("#Email", OdbcType.VarChar).Value = email;
exe.Parameters.Add("#Address", OdbcType.VarChar).Value = address;
exe.Parameters.Add("#Age", OdbcType.Int).Value = age;
conn.Open();
exe.ExecuteNonQuery(); // ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6.
This code throws me Too few parameters. error when I am trying to execute query. The database is fine, it works fine when I hardcode values into a query, instead of using parameters.
Thank you.
From MSDN:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Rewrite your query to
OdbcConnection conn = new OdbcConnection(connString);
String query = "INSERT INTO customer (custId, custName, custPass, "+
"custEmail, custAddress, custAge) VALUES (" +
"?, ?, ?, ?, ?, ?)";
Order of Parameter counts!
EDIT: Parameter can be added this way:
OdbcCommand exe = new OdbcCommand(query, conn);
exe.Parameters.Add("ID", OdbcType.UniqueIdentifier).Value = id;
exe.Parameters.Add("Name", OdbcType.VarChar).Value = name;
exe.Parameters.Add("Pass", OdbcType.VarChar).Value = pass;
exe.Parameters.Add("Email", OdbcType.VarChar).Value = email;
exe.Parameters.Add("Address", OdbcType.VarChar).Value = address;
exe.Parameters.Add("Age", OdbcType.Int).Value = age;
One of your columns in your query does not exist.
Please check your column names.
Typically you'll see this when you misspell a column name in your SQL statement. Are you sure of those column names (custId, custName, etc.)?
try changing pass to passw maybe it is getting mixed up with asp identifier...

Categories