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();
}
Related
I am unable to send lasted inserted autoincrement id value to another table
this is my code
i am getting error is Must declare the scalar variable "#userid".
int ID;
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()", cn);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
cmd.ExecuteNonQuery();
ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
SqlCommand cmd2 = new SqlCommand("insert into sampfk values(#emailid,#address,#userid)", cn);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text);
cmd2.Parameters.AddWithValue("#userid", ID);
cn.Open();
cmd2.ExecuteNonQuery();
cn.Close();
cmd.Dispose();
TextBox3.Text = "";
TextBox4.Text = "";
I think I got your problem.you have written
SqlCommand cmd2 = new SqlCommand("insert into sampfk values (#userid, #address, #emailid)", cn);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text)
but executing
cmd2.ExecuteNonQuery();
you should add parameter in cmd2 not cmd like as
cmd2.Parameters.AddWithValue("#userid", ID);
cmd2.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd2.Parameters.AddWithValue("#address", TextBox4.Text)
You can do above in single step, you should use using more and try to nest query if possible. Opening TCP connection frequently has some acknowledgement overheads.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["samplefkConnectionString"].ConnectionString))
{
string query = #"INSERT INTO sampdb VALUES (#name,#phone);
INSERT INTO sampfk VALUES (SCOPE_IDENITTY(), #address, #emailid); ";
using (SqlCommand cmd = new SqlCommand(query, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cmd.ExecuteNonQuery();
}
}
Check the following line.
ID = Convert.ToInt32(cmd.ExecuteScalar());
If this doesn't return anything, then use a default value for ID, maybe 0.
Or add a default value in the declaration as int id = 0;
try this
using (SqlConnection cn = new SqlConnection(connectionStr))
{
string sql1 = "insert into sampdb values(#name,#phone);"+ "Select Scope_Identity()";
using (SqlCommand cmd = new SqlCommand(sql1, cn))
{
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#phone", TextBox2.Text);
cn.Open();
ID = cmd.ExecuteNonQuery();
}
//ID = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();
TextBox1.Text = "";
TextBox2.Text = "";
string sql2 = "insert into sampfk values (#userid, #address, #emailid)";
using (SqlCommand cmd = new SqlCommand(sql2, cn))
{
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#emailid", TextBox3.Text);
cmd.Parameters.AddWithValue("#address", TextBox4.Text);
cn.Open();
cmd.ExecuteNonQuery();
}
con.Dispose();
con.Close();
}
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 use this code to update data that are in the textboxes... this code is in the update button and once i made the changes and clicked the button the error message appears
try
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE student_info SET SEM = #SEM, STUDENT_NO = #STUDENT_NO, LASTNAME = #LASTNAME" +
", FIRSTNAME = #FIRSTNAME, MIDDLENAME = #MIDDLENAME, CITY = #CITY, STREET = #STREET, GENDER = #GENDER" +
", COURSE = #COURSE, YEAR = #YEAR, SECTION = #SECTION, BIRTHDAY = #BIRTHDAY Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#SEM", sem_combo.Text);
cmd.Parameters.AddWithValue("#STUDENT_NO", studentNo_txt.Text);
cmd.Parameters.AddWithValue("#LASTNAME", lname_txt.Text);
cmd.Parameters.AddWithValue("#FIRSTNAME", fname_txt.Text);
cmd.Parameters.AddWithValue("#MIDDLENAME", mname_txt.Text);
cmd.Parameters.AddWithValue("#CITY", address_txt.Text);
cmd.Parameters.AddWithValue("#STREET", street_txt.Text);
cmd.Parameters.AddWithValue("#GENDER", gender_combo.Text);
cmd.Parameters.AddWithValue("#COURSE", program_combo.Text);
cmd.Parameters.AddWithValue("#YEAR", yr_combo.Text);
cmd.Parameters.AddWithValue("#SECTION", section_combo.Text);
cmd.Parameters.AddWithValue("#BIRTHDAY", bday.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL, CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Check in This Line
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL,
CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
Change To
cmd.Parameters.Clear();
cmd.CommandText = "UPDATE contacts SET EMAIL = #EMAIL,
CELL_NO = #CELL_NO Where STUDENT_NO = #STUDENT_NO";
cmd.Parameters.AddWithValue("#EMAIL", email_txt.Text);
cmd.Parameters.AddWithValue("#CELL_NO", contact_txt.Text);
cmd.Parameters.AddWithValue("#STUDENT_NOL",studentNo_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
you are clear the parameters, but after that use #STUDENT_NO parameter. This parameter is not declare any where after clear ther parameters
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.
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