Error in Updating a Record - c#

Hello Everyone I'm new in here. I am currently making an asp.net project monitoring module. At this moment I am in the process of editing the project form and adding resources to the selected task in a project.
I'm having a problem in saving the record. Everytime I save the record it says
"Column name or number of supplied values does not match table
definition."
In my ProjectTasks Table I have RefNo(PK), TaskID(FK), Name and Description
Name - refers to the Task Name
Description - refers to the Task Description
What I want to happen is that my Resource Tables TaskID(FK) will be updated when I clicked the save button. As of now when I add a Resource from a task the TaskID = 0.
protected void btnSave_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO ProjectTasks VALUES (#Name, #Description); " +
"SELECT TOP 1 TaskID FROM ProjectTasks ORDER BY TaskID DESC;";
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Description", txtDescription.Text);
int taskID = (int)cmd.ExecuteScalar();
con.Close();
con.Open();
cmd.CommandText = #"UPDATE Resource_Materials SET TaskID=#TaskID WHERE TaskID=0; " +
"UPDATE Resource_Equipments SET TaskID=#TaskID WHERE TaskID=0; " +
"UPDATE Resource_Vehicles SET TaskID=#TaskID WHERE TaskID=0; " +
"UPDATE Resource_Contractors SET TaskID=#TaskID WHERE TaskID=0;";
cmd.Parameters.AddWithValue("#TaskID", taskID);
cmd.ExecuteNonQuery();
con.Close();
Helper.AddLog("1", "Add", "Assigned Resources to Task");
Response.Redirect("~/Projects/Default.aspx");
}
Sorry about my grammar I'm just a student.

You said
ProjectTasks Table I have RefNo(PK), TaskID(FK), Name and Description
In such case, your INSERT query should look like below instead, specify the exact column name you are trying to insert values and as well you are missing TaskID(FK) column in your current insert query
INSERT INTO ProjectTasks(TaskID, Name, Description)
VALUES (#TaskID, #Name, #Description);

In an insert statement, we need to supply the column names when we don't want to specify values for all columns. If we don't do this we need so supply values for all columns.
In your case, you just want to provide values for Name and Description so you can do something like:
INSERT INTO ProjectTasks(Name, Description) VALUES (#Name, #Description);

Your logic is misleading..
Your ProjectTasks has 4 columns but you try to insert 2 column value in your insert statement without declaring them after your table name as ProjectTasks (Name, Description).
But this still generate a problem because your first column is PK and second one is FK. Since FK can be null but PK can't be null as far as I know, that's why you need to re-think your inserting logic.
But even if you fix it, your code still has a problem. Since you set a new string to your CommandText property, your #Name and #Description parameters were still belongs on your cmd object. That's why on ExecuteNonQuery line, your cmd will have 3 parameters as #Name, #Description and #TaskID but your command has only 1 parameter. As you can see, you will get an error such as; the parameter you supplied and command doesn't match or something. In such a case, you need to Clear() your parameters before you set new CommandText or generate a new SqlCommand object as cmd = new SqlCommand()
Also use using statement to dispose your connection and commands automatically instead of calling .Close() or .Dispose() methods manually.
And don't use AddWithValue method anymore. It may generate unexpected results sometimes. Use Add method overloads to specify your parameter type and it's size.

Solved it by removing ExecuteScalar and by replacing INSERT statement into UPDATE statement instead.
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE ProjectTasks SET Name=#Name, Description=#Description " +
"WHERE TaskID=#TaskID; " +
"SELECT TOP 1 TaskID FROM ProjectTasks ORDER BY TaskID DESC;";
cmd.Parameters.AddWithValue("#Name", txtName.Text);
cmd.Parameters.AddWithValue("#Description", txtDescription.Text);
cmd.Parameters.AddWithValue("#TaskID", Request.QueryString["ID"].ToString());
cmd.CommandText = #"UPDATE Resource_Materials SET TaskID=#TaskID WHERE TaskID=0; " +
"UPDATE Resource_Equipments SET TaskID=#TaskID WHERE TaskID=0; " +
"UPDATE Resource_Vehicles SET TaskID=#TaskID WHERE TaskID=0; " +
"UPDATE Resource_Contractors SET TaskID=#TaskID WHERE TaskID=0;";
cmd.ExecuteNonQuery();
con.Close();
Helper.AddLog("1", "Add", "Assigned Resources to Task");
Response.Redirect("~/Projects/Default.aspx");

Related

Number of query values and destination fields are not the same OLEDB

I getting an error while i'm trying to insert data to my DB.
This is the error.
"System.Data.OleDb.OleDbException: 'Number of query values and destination fields are not the same.'".
cmd.CommandText = "INSERT INTO [clients]([Firstname],[Lastname],[Email],[Phonenumber],[Address],[CNP],[SeriesCI],[NumberCI],[Sex],[CUI],[J],[Personaldescription],[Temperament],[Provenance],[Registerdata],[Idteam],[NumeAgent])" +
"Select #f,#l,#e,#ph,#add,#cnp,#ser,#n,#sex,#cui,#j,#pd,#te,#prov,#reg,team.[id] from team where team.[Email]=#email,#agent";
cmd.Parameters.AddWithValue("#f", materialSingleLineTextField16.Text);
cmd.Parameters.AddWithValue("#l", materialSingleLineTextField15.Text);
cmd.Parameters.AddWithValue("#e", materialSingleLineTextField14.Text);
cmd.Parameters.AddWithValue("#ph", materialSingleLineTextField13.Text);
cmd.Parameters.AddWithValue("#add", materialSingleLineTextField6.Text);
cmd.Parameters.AddWithValue("#cnp", materialSingleLineTextField1.Text);
cmd.Parameters.AddWithValue("#ser", materialSingleLineTextField3.Text);
cmd.Parameters.AddWithValue("#n", materialSingleLineTextField2.Text);
cmd.Parameters.AddWithValue("#sex", gender);
cmd.Parameters.AddWithValue("#cui", materialSingleLineTextField4.Text);
cmd.Parameters.AddWithValue("#j", materialSingleLineTextField5.Text);
cmd.Parameters.AddWithValue("#pd", richTextBox2.Text);
cmd.Parameters.AddWithValue("#te", bunifuDropdown1.selectedValue);
cmd.Parameters.AddWithValue("#prov", bunifuDropdown2.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#email", Form1.Email);
cmd.Parameters.AddWithValue("#agent", NumeAgent);
In DB (clients) i have 17 columns + id (but the id is auto increment).
What am I doing wrong?
clients
team
cmd.CommandText = "INSERT INTO [clients]([Firstname],[Lastname],[Email],[Phonenumber],[Address],[CNP],[SeriesCI],[NumberCI],[Sex],[CUI],[J],[Personaldescription],[Temperament],[Provenance],[Registerdata],[NumeAgent],[Idteam])" + "Select #f,#l,#e,#ph,#add,#cnp,#ser,#n,#sex,#cui,#j,#pd,#te,#prov,#reg,[Firstname]+' '+[Lastname] from team where [Email]=#email,team.[id] from team where team.[Email]=#email";
Try changing your INSERT statement like this:
cmd.CommandText = "INSERT INTO [clients]([Firstname],[Lastname],[Email],[Phonenumber],[Address],[CNP],[SeriesCI],[NumberCI],[Sex],[CUI],[J],[Personaldescription],[Temperament],[Provenance],[Registerdata],[Idteam],[NumeAgent])" +
"Select #f,#l,#e,#ph,#add,#cnp,#ser,#n,#sex,#cui,#j,#pd,#te,#prov,#reg,team.[id],#agent from team where team.[Email]=#email";
Note, I have moved the ,#agent part from the end of WHERE clause to the end of SELECT field list.
However, I'm not sure your overall idea is correct. If you are selecting values to be inserted from the team table, why to also specify them as Command parameters?

insert data in a field on the basis of condition, in MySql (PhpMyadmin)

I have: Crew table with every field full of data except one single field, that is, Crew_status... it represents the availability of any crew, that whether he/she is available for next flight or not.
My problem: i want to insert "unavailable" in the crew_status of that specific crew who has been allocated to some flight. To do this, i will have to use where clause inorder to figure out whether flight_name is empty or has some data. if it is empty(which means crew has not been allocated yet), I want to insert available in its crew_status field.. and if it is not empty(which means crew has been allocated to any flight), I want to insert unavailable in its crew_status field....
.
how can i do that ? I am having error
syntax error near: "='unavailable' where flight_name='fl243'"
My Module is:
public void availability(string table_name, string field_name, string where_clause1, string where_clause2, string status)
{
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update " + table_name + "set "+field_name+"='" + status + "' where " + where_clause1+"='"+where_clause2+"'";
cmd.ExecuteNonQuery();
con.Close(); }
NOTE: table_name="crew" , field_name="crew_status" Whereclause1="flight_name" , Whereclause2="fl243" , status="unavailable"
Give a space between table_name and set
"update " + table_name + " set "+field_name+"='" + status + "' where " + where_clause1+"='"+where_clause2+"'";

How to use LAST_INSERT_ID() in c# windows form?

In database I have three tables-
patient(patientID,fName,lName)
illness(diseaseID,diseaseName)
patientDisease(patientID, diseaseID, dateChecked)
patientID and diseaseID are index.
So on in c# I have three textboxes fNameTxt and lNameTXT, diseaseTxt.I want to store the name in patient table and disease name in illness table. Besides, I have to record patientID and diseaseID in patientDisease table as well. For patient table, I used following code. I knew, I can use
SET #variable = LAST_INSERT_ID()
to get the id, but realised c#(visual studio) doesnt recognize it. Basically, I couldnt make the overall statement. Could anybody help me to get through this condition please.
string connStr = #"server=localhost; DATABASE=mario;User ID=root;Password=;";
MySqlConnection conn1 = new MySqlConnection();
conn1.ConnectionString = connStr;
MySqlCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO patient(patientID,fName, lName)"
+ "Values("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');";
conn1.Open();
cmd.ExecuteNonQuery();
I searched some other questions here, but they are almost about suggesting the use of LAST_INSERT_ID() but not how to use it.
It will be much better if you use stored procedures
INSERT INTO patient (patientID,patientID,lName)
VALUES("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');
SET #last_id_in_patient = LAST_INSERT_ID();
INSERT INTO patientDisease (patientID,diseaseID,dateChecked)
VALUES( #last_id_in_patient ,NULL,'text'); # use ID in second table";
Now You can update your PatientDisease table for particular PatientId.
You can use this to get the last inserted id:
"SELECT * FROMtable(column) WHERE id = last_insert_id();
And use this if you want to insert a last id:
"INSERT INTO table(column) VALUES (LAST_INSERT_ID())";
Hope this might be useful.

How to initialize Access Number field in C-Sharp

I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements

Inserting the max value of one comlumn from one table to another table

I am updating a database with a new registered user. they will then be given a userid. I want to use that number when updating there location in another table. but i dont know what the user id will be. (it is autoincrement number) So i was thinkning i would update the first table. And then select the maximum user id and insert that id as the location user id in the other table but I cant get it to work.
Here is the code.
String StrSQL = "INSERT INTO Fastelejer (Fornavn,Efternavn) VALUES ('" + fornavn + "','" +
Efternavn + "')";
OleDbCommand InsertCommand = new OleDbCommand(StrSQL, conn);
InsertCommand.ExecuteNonQuery();
StrSQL = "INSERT INTO Bådpladser (Fastelejerid) SELECT MAX (Fastelejerid) FROM
StrSQL = "INSERT INTO Bådpladser (Fastelejerid) SELECT MAX (Fastelejerid)FROM
Fastelejer WHERE Pladsnummer = " + Pladsnummer;
The pladsnummer represents the input for their location. So the registration should put the user id into the location that is chosen.
In MS Access, "autoincrement" is usually called "identity". You can use the special ##IDENTITY variable to retrieve the ID of the last inserted identity column. Once you know the new ID, you can add it as a parameter in the second insert, like:
command.CommandText = "INSERT Table1 (...) values (...); SELECT ##IDENTITY";
var identity = (int) command.ExecuteScalar();
command.CommandText = "INSERT Table2 (user_id, ...) VALUES (#user_id, ...)";
command.Parameters.AddWithValue("#user_id", identity);
command.ExecuteNonQuery();

Categories