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

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?

Related

Error in Updating a Record

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");

Inserting values into table from textboxes & from another table's foreign key C#

Im trying to insert into a table values from textboxes AND to retrieve a foreign key id from another table and insert that also.
So I have a users table which contains UserId and I want this inserted into a nutrition diary which includes all the data that comes from textboxes(ie Weight, Height, Date etc)
I am retrieving the MemberId by using a session to track the username(lblRegistered)
Here is my code:
SqlConnection con = new SqlConnection("path for my connection");
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM Members where Username='" + lblRegistered.Text + "'", con);
con.Close();
con.Open();
cmd.CommandText = "INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId) values ('" + txtWeight.Text + "','" + txtHeight.Text + "','" + txtBmi.Text + "','" + txtDate.Text + "','" + txtWater.Text + "','" + txtCalorie.Text + "', Select Users.UserId From Users where (Users.Username= '" + lblRegistered.Text + "'))";
cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
Response.Redirect("Success.aspx");
The error is close to Select Users part.
Any help would be greatly appreciated!
First thing would be to read up on parameterized SQL queries. The code you have there is completely open to SQL injection attacks.
This is a good resource for that: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Then for the problem you would be better off using a Stored Procedure to do the work. Something along the lines of :
CREATE PROCEDURE Nutrition_Insert
#weight varchar(10),
#height varchar(10),
#bmi varchar(10),
#date varchar(10),
#username varchar(10),
//etc for your fields
AS BEGIN
DECLARE #memberId varchar(10)
SELECT #memberId = UserId From Users where Username = #username
INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId)
values (#weight, #height, #bmi, ....., #memberId)
END
Note - I've made some assumptions there as I don't know your data types, they all look like strings, but not knowing the size of the varchar used, I picked an arbitary value. Replace the (10) with the actual field size.
If you must use embedded SQL - then this is how you parameterize it. I've also fixed the insert statement to pull the MemberId from the Members table as part of the insert.
using (var conn = new SqlConnection("YOUR CONNECTION STRING"))
{
conn.Open();
using (
var cmd = new SqlCommand(
"INSERT INTO Nutrition(...fields...) SELECT #Weight, #Height, #Bmi,...., Members.MemberId FROM Members WHERE Members.Username = #Username", conn)
)
{
cmd.Parameters.AddWithValue("#Weight", txtWeight.Text);
cmd.Parameters.AddWithValue("#Height", txtHeight.Text);
...
cmd.Parameters.AddWithValue("#Username", lblRegistered.Text);
cmd.ExecuteNonQuery();
}
conn.Close();
}
You'll notice the using statements too. This will make sure your connection are disposed of cleanly.
Hope that helps.
Thanks Richard..that worked very well on the problem.
I am just trying to do the same technique on a different page but this time it will have 2 where clauses
var cmd = new SqlCommand("INSERT INTO AssignPlan(Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) Select #Reps, #Sets,#WeightOrTime,#Date, Members.MemberId From Members Where Members.Username=#name,ExerciseDisplay.ExerciseId From ExerciseDisplay Where ExerciseDisplay.ExerciseName=#Exercise", conn)
It's showing up an error from the syntax. Can this be achieved?

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

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.

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