access 2003
vs 2010 c#
I cannot see where I have gone wrong. There is no error but no data is being updated. I have the insert, delete and edit working but I don't know why I can't get this to work. Please can someone kindly help me here, thanks in advance...
connection string
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:..\TempDB.mdb");
Update method...
private void btnUpdate_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE [Family] SET [FirstName] = ?, [LastName] = ?, [FamilyDOB] = ?, [Medical] = ? WHERE [ID] = ?";
//tried this as well
//cmd.CommandText = "UPDATE [Family] SET [FirstName] = FirstName, [LastName] = #LastName, [DOB] = #StudentDOB, [Medical] = #Medical WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", txtFamID.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FamDOB", txtFamDOB.Text);
cmd.Parameters.AddWithValue("#Medical", txtMedical.Text);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
Supply the parameter values in the same order as they appear in the SQL statement.
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FamDOB", txtFamDOB.Text);
cmd.Parameters.AddWithValue("#Medical", txtMedical.Text);
cmd.Parameters.AddWithValue("#ID", txtFamID.Text);
OleDB plus MS Access doesn't care about the parameter names, only their order.
The OLE DB.NET Framework Data Provider uses positional parameters that are marked with a question mark (?) instead of named parameters.
Change this:
cmd.Parameters.AddWithValue("#ID", txtFamID.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FamDOB", txtFamDOB.Text);
cmd.Parameters.AddWithValue("#Medical", txtMedical.Text);
to:
cmd.Parameters.AddWithValue("?", txtFamID.Text);
cmd.Parameters.AddWithValue("?", txtFirstName.Text);
cmd.Parameters.AddWithValue("?", txtLastName.Text);
cmd.Parameters.AddWithValue("?", txtFamDOB.Text);
cmd.Parameters.AddWithValue("?", txtMedical.Text);
More: OleDbParameter Class
Related
I do not know why I am getting this error:
C# Code:
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=***;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO student (studentID, studentFirstName, studentLastName, studentUserName, studentPassword) VALUES (#userID, #, #FirstName, #LastName, #Username, #Password);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
connection.Open();
cmd.Connection = connection;
cmd.ExecuteNonQuery();
MessageBox.Show("Saved");
connection.Close();
}
It may due to me overlooking something.
Error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data
Additional information: Column count doesn't match value count at row 1
Format out your code and you'll see all the syntactic problems clearly:
string connectionString =
"datasource=localhost;port=3306;database=project;username=***;password=***;";
using (MySqlConnection connection = new MySqlConnection(connectionString)) {
connection.Open();
//DONE: keep sql readable
string sql =
#"INSERT INTO student (
studentID,
studentFirstName,
studentLastName,
studentUserName,
studentPassword)
VALUES (
#userID,
#FirstName, -- wrong # param
#LastName,
#Username,
#Password);";
//DONE: wrap IDisposable into using
using (MySqlCommand cmd = new MySqlCommand(sql)) {
cmd.CommandType = CommandType.Text; // redundant
cmd.Connection = connection;
//DONE: separate code with new lines
// wrong parameter name
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));
cmd.Parameters.AddWithValue("#FirstName", textBoxFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", textBoxLastName.Text);
cmd.Parameters.AddWithValue("#UserName", textBoxUsername.Text);
cmd.Parameters.AddWithValue("#Password", textBoxPassword.Text);
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Saved");
You are adding an additional parameter in your values clause (#userID, #,
also add the "#" before user id
cmd.Parameters.AddWithValue("userID", Convert.ToInt32(textBoxUserID.Text));
should be
cmd.Parameters.AddWithValue("#userID", Convert.ToInt32(textBoxUserID.Text));
I have to update some values in table row if UserId = Session["username"]
but its showing error:
ExecuteNonQuery: Connection property has not been initialized.
can any one know what i am doing wrong here a Session["username"] have its value i have checked.
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration (FirstName,LastName,Password,LastName,EmaildId,UserId) " +
"VALUES (#FirstName, #LastName, #Password, #EmaildId, #UserId) WHERE UserId='" + Session["username"] + "'";
var cmd = new SqlCommand(qry);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
You need to tell the SqlCommand-object which connection to use, change this line
var cmd = new SqlCommand(qry, conn7);
Two Problems
In SQLCOMMAND you should specify querystring,connection
Your update query syntax is wrong
..try below
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = "UPDATE Registration
SET FirstName=#FirstName,LastName=#LastName,Password=#Password,
EmaildId=#EmaildId,UserId=#UserId WHERE UserId=#UserId1";
var cmd = new SqlCommand(qry,conn7);
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId1", Session["username"].ToString());
conn7.Open();
// cmd7.ExecuteNonQuery();
cmd.ExecuteNonQuery();
conn7.Close();
Use Parameters for all you input, don't concatenate strings in queries.
As for your error, you need to specify the connection that the command needs to use:
SqlConnection conn7 = new SqlConnection(#"Data Source=SANJAY-PC\SQLEXPRESS;
Initial Catalog=dev;User ID=sa;Password=sa#123;Pooling=False");
var qry = " UPDATE Registration SET FirstName = #FirstName, LastName = #LastName,"
+ " Password = #Password, EmaildId = #EmaildId WHERE UserId = #UserCondition";
var cmd = new SqlCommand(qry, conn7 );
cmd.Parameters.AddWithValue("#FirstName", Firstname_Update.Text);
cmd.Parameters.AddWithValue("#LastName", Lastname_Update.Text);
cmd.Parameters.AddWithValue("#Password", Password_Update.Text);
cmd.Parameters.AddWithValue("#EmaildId", EmailIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserId", UserIdUpdate.Text);
cmd.Parameters.AddWithValue("#UserCondition", Session["username"].ToString());
conn7.Open();
cmd.ExecuteNonQuery();
conn7.Close();
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;
'Set' Missing
I would like to update/edit my user data in Employee table in access database.
When i complete the fields that i want to change (name , last name, etc.), it gives me data updated but when i refresh the table, the data hasn't changed - been updated.
Changes i want to perform for example - Change name from Luke to Taylor, etc.
Where have i gone wrong? Where is the mistake in the code and does my code for adding users to database somehow have influence my update code?
My code for adding users is almost the same as for the update, except for query, and it works fine.
private void button2_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Update Employee set Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #ID";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User updated!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Code for adding user data
private void button1_Click(object sender, EventArgs e)
{
try
{
command.Connection = myConnection;
command.CommandText = "Insert into Employee (ID, Name, LastName, UserName, Password, E_mail, Address)" + "values (#ID, #Name, #LastName, #UserName, #Password, #E_mail, #Address)";
command.Parameters.AddWithValue("#ID", userID.Text);
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
command.ExecuteNonQuery();
MessageBox.Show("User added!");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for the replies and help
I still have no solution for this. I've tried so many things but i just don't get the right answer.
My current code
try
{
OleDbConnection myConnection = new OleDbConnection("\\DATABASE PATH");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myConnection;
cmd.CommandText = "UPDATE Employees SET Name = #Name, LastName = #LastName, UserName = #UserName, Password = #Password, E_mail = #E_mail, Address = #Address WHERE ID = #";
cmd.Parameters.AddWithValue("#ID", userID.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#LastName", lastName.Text);
cmd.Parameters.AddWithValue("#UserName", userName.Text);
cmd.Parameters.AddWithValue("#Password", pass.Text);
cmd.Parameters.AddWithValue("#E_mail", eMail.Text);
cmd.Parameters.AddWithValue("#Address", address.Text);
myConnection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("User successfully added.");
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Its because your ID in where condition.
You are also changing/updating your ID through:
command.Parameters.AddWithValue("#ID", userID.Text);
This new ID is not found by compiler in Database since you kept where ID=#ID condition in your query.
When you just updates name and other fields then query becomes:
Update Employee set Name = 'Name', LastName = 'LastName', UserName = 'UserName', Password = 'Password', E_mail = 'E_mail', Address = 'Address' WHERE ID = ''";
Your ID might remain blank in that case.
Try the following in your update code:
command.CommandText = "UPDATE Employee SET [Name] = ?, LastName = ?, UserName = ?, [Password] = ?, [E_mail] = ?, Address = ? WHERE [ID] = ?";
command.Parameters.AddWithValue("#Name", name.Text);
command.Parameters.AddWithValue("#LastName", lastName.Text);
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", pass.Text);
command.Parameters.AddWithValue("#E_mail", email.Text);
command.Parameters.AddWithValue("#Address", address.Text);
command.Parameters.AddWithValue("#ID", userID.Text);
The parameters must be in the order in which they appear in the CommandText. This answer was suggested by: Microsoft Access UPDATE command using C# OleDbConnection and Command NOT working
The reasons for this is outlined here: http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters(v=vs.110).aspx
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used.
I cannot figure out what I am doing wrong here, in the debugger when I set breakpoints the strings all have string values in them, but when it comes time to insert them into the table, nothing gets put in.
the table is defined as follows
CREATE TABLE [dbo].[tblMissEvents] (
[EventID] INT IDENTITY (1, 1) NOT NULL,
[EventTime] NVARCHAR (MAX) NULL,
[MIS_Event_Action] VARCHAR (50) NULL,
[Bogey_Type] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([EventID] ASC)
);
my code:
string date = DateTime.Now.ToString();
string MISaction = text1.Text;
string BogeyType = text2.Text;
try
{
con = new SqlConnection();
con.ConnectionString =
#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type) Values (#date, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
con.Close();
Any thoughts?? I don't get an exception, just no entry into my table.
edit for Arshad:
con = new SqlConnection();
con.ConnectionString =
#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT into tblMissEvents (MIS_Event_Action, Bogey_Type) Values (#date, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
cmd.Connection = con;
cmd.ExecuteNonQuery();
UPDATE:: The code was fine, it was making a copy of the DB in my bin\Debug directory and thats where all the data was going. Probably something with my connection string setup. Thanks all!
You can pass null value also as :
cmd.CommandText =
"INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type)
Values (#eventTime, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#eventTime", DBNull.Value);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
Update 1
cmd.CommandText =
"INSERT into tblMissEvents (EventTime,MIS_Event_Action, Bogey_Type)
Values
(#date, #MISaction, #BogeyType)";
Update 2
int RowUpdated=cmd.ExecuteNonQuery();
MessageBox.Show("Number of row updated"+RowUpdated);
I make a program that saves and update a data from the database, I can save and read data, I can also update but the problem is, I can't select the "ID" as the index, here is my sample code using "ID" as the index,
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();
}
and here is my update code that works, but the index is the "firstname",
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE FirstName = #firstname";
//cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();`
}
It works but the problem is I can't update the "FirstName", Is there a way that I can also update the Firstname? or use the "ID" as the index? thanks
I don't know what database you are going against, however, I don't know if the OleDB is being picky on the ordinal sequence of your parameters. ie: Have you tried putting your "ID" parameter in the last position to match the actual order of the fields of your update command? I don't know if it's throwing it out.
You should add the following code after the last line of ID:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = #firstname, LastName = #lastname, Age = #age, Address = #address, Course = #course WHERE [ID] = #id";
cmd.Parameters.AddWithValue("#firstname", textBox1.Text);
cmd.Parameters.AddWithValue("#lastname", textBox2.Text);
cmd.Parameters.AddWithValue("#age", textBox3.Text);
cmd.Parameters.AddWithValue("#address", textBox4.Text);
cmd.Parameters.AddWithValue("#course", textBox5.Text);
cmd.Parameters.AddWithValue("#id", int.Parse(label7.Text));
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Update Success!");
cn.Close();
}