fatal error encountered during command execution during update - c#

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

Related

One to many relation data sending

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

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I'm a beginner in using Asp.net MVC5, I am trying to update the records to the database and this always show up.
Here is the screenshot
Here is the code:
SqlConnection con = new SqlConnection(DAL.cs);
con.Open();
SqlCommand com = new SqlCommand("UPDATE Student SET LastName = #LastName," +
"FirstName = #FirstName," +
"MiddleName = #MiddleName," +
"WHERE ID = #ID", con);
com.Parameters.AddWithValue("#ID", SqlDbType.Int).Value = s.ID;
com.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = s.LastName;
com.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = s.FirstName;
com.Parameters.AddWithValue("#MiddleName", SqlDbType.VarChar).Value = s.MiddleName;
com.ExecuteNonQuery();
con.Close();
strong text
Remove the comma after the last parameter:
SqlConnection con = new SqlConnection(DAL.cs);
con.Open();
SqlCommand com = new SqlCommand("UPDATE Student SET LastName = #LastName," +
"FirstName = #FirstName," +
"MiddleName = #MiddleName " +
"WHERE ID = #ID", con);
com.Parameters.AddWithValue("#ID", SqlDbType.Int).Value = s.ID;
com.Parameters.AddWithValue("#LastName", SqlDbType.VarChar).Value = s.LastName;
com.Parameters.AddWithValue("#FirstName", SqlDbType.VarChar).Value = s.FirstName;
com.Parameters.AddWithValue("#MiddleName", SqlDbType.VarChar).Value = s.MiddleName;
com.ExecuteNonQuery();
con.Close();

Update statement doesn't update my data

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.

C# Get insert id with Auto Increment

I am using this method to insert a row into a table:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
"(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
I hav also id column that have Auto Increment .
And i want to know if it possible to get the id that is created when i insert a new row.
You can access the MySqlCommand LastInsertedId property.
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
+ "VALUES(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
**cmd.Parameters["#clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Basically you should add this to end of your CommandText:
SET #newPK = LAST_INSERT_ID();
and add another ADO.NET parameter "newPK". After command is executed it will contain new ID.

Oledb Update command

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

Categories

Resources