Error in ExecuteNonQuery() - c#

I am getting continuously an error on ExecuteNonQuery();. I have tried many ways but don't know where I am wrong.
I am using float data type in orderid, price, quantity, discount, order price columns in SQL Server.
Kindly help.
string query = "Insert into dbo.orders (OrderType,Product_Name,Product_Category,Product_Quantity,Product_Price,Date,Discount) values(#txt_rdvalue,#cb_oname,#cb_ocat,#cb_oqty,#txt_oprice,#Date,#txt_disc)";
if (string.IsNullOrWhiteSpace(txt_rdvalue.Text) || string.IsNullOrWhiteSpace(cb_oname.Text) || string.IsNullOrWhiteSpace(cb_ocat.Text) || string.IsNullOrWhiteSpace(cb_oqty.Text))
{
lbl_incorrect.Text = "please fill up all the fields";
lbl_incorrect.Visible = true;
}
else
{
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Pizza Mania;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#txt_rdvalue",txt_rdvalue.Text);
cmd.Parameters.AddWithValue("#txt_orderid",txt_orderid.Text);
cmd.Parameters.AddWithValue("#cb_oname", cb_oname.SelectedText);
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedText);
cmd.Parameters.AddWithValue("#cb_oqty", cb_oqty.SelectedValue);
cmd.Parameters.AddWithValue("#txt_oprice", (txt_oprice.Text));
cmd.Parameters.AddWithValue("#txt_disc", txt_rdvalue.Text);
cmd.Parameters.Add(new SqlParameter("#Date", dateTimePicker1.Value.Date));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
}
}
}
The error message I am getting:
The parameterized query '(#txt_rdvalue nvarchar(8),#txt_orderid
int,#cb_oname nvarchar(40' expects the parameter '#cb_oqty', which was
not supplied

yes i have done it. The convert to double thing works
thankyou all
Appriciated.[enter link description here][1]
cmd.Parameters.AddWithValue("#txt_rdvalue",txt_rdvalue.Text);
cmd.Parameters.AddWithValue("#txt_orderid",Convert.ToDouble(txt_orderid.Text));
cmd.Parameters.AddWithValue("#cb_oname", cb_oname.SelectedText);
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedText);
cmd.Parameters.AddWithValue("#cb_oqty", Convert.ToDouble(cb_oqty.SelectedValue));
cmd.Parameters.AddWithValue("#txt_oprice",Convert.ToDouble((txt_oprice.Text)));
cmd.Parameters.AddWithValue("#txt_disc",Convert.ToDouble(txt_disc.Text));
cmd.Parameters.Add(new SqlParameter("#Date", dateTimePicker1.Value.Date));
[1]: http://www.stackoverflow.com/alygorejaanswers

You are providing #txt_orderid(cmd.Parameters.AddWithValue("#txt_orderid",txt_orderid.Text);) parameter which doesn't exists.Check your code once again.
If it's autoincrement coloumn why are you providing this.
Also datatype mismatching is happening.

Related

"Invalid column name" when trying to insert data into database using SQL

I'm trying to insert new values into my database using visual studio and here is my code:
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = dbconnectionstring;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Data_ConfigInfo (TypeID, Name, ValidFromDate, ValidToDate, ValidFromSOP, ValidToSOP, Description)" +
"VALUES(#TypeID, #Name, #ValidFromDateTime, #ValidToDateTime, #ValidFromSOP, #ValidToSOP, #Description)";
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
if(Logg.ValidFrom.Equals(null)) {
cmd.Parameters.AddWithValue("#ValidFromDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidFromDateTime", Logg.ValidFrom);
}
if (Logg.ValidTo.Equals(null))
{
cmd.Parameters.AddWithValue("#ValidToDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidToDateTime", Logg.ValidFrom);
}
cmd.Parameters.AddWithValue("#ValidFromSOP", Logg.ValidFromSOP);
cmd.Parameters.AddWithValue("#ValidToSOP", Logg.ValidToSOP);
cmd.Parameters.AddWithValue("#Description", Logg.Description);
cmd.ExecuteNonQuery();
conn.close();
conn.dispose();
But at the line
cmd.ExecuteNonQuery();
I get the error
invalid column name for ValidToDateTime and ValidFromDateTime.
Both are datetime variables. I can't seem to find the error. Any ideas?
This is how my datatable looks
Your DB table has columns ValidFromDateTime, ValidToDateTime, but your column list in the INSERT statement has ValidFromDate, ValidToDate. Are you sure that it is not a typo when posting here?
Did you forgot '#'?
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
cmd.Parameters.AddWithValue("#TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("#Name", Logg.Name);

the parameterized query error c#

When i select an item from combo box(cb_oname) and enter the order then the program crashes and give error at executenonquery().i have highlighted below
Actually this code runs when i click the submit order button. the cb_ocat is the category of the item its data type is vnarchar(50)
string query = #"Insert into dbo.orders
(OrderType,OrderID,Product_Name, Product_category,Product_Quantity,
Product_Price,Date,Discount,Order_Price,Phone) values
(#txt_rdvalue,#txt_orderid,#cb_oname,#cb_ocat,#cb_oqty,
#txt_oprice,#Date,#txt_disc,#txt_orderprice,#txt_call)";
if (string.IsNullOrWhiteSpace(txt_rdvalue.Text) || string.IsNullOrWhiteSpace(txt_orderid.Text) || string.IsNullOrWhiteSpace(cb_oname.Text) || string.IsNullOrWhiteSpace(cb_ocat.Text) || string.IsNullOrWhiteSpace(cb_oqty.Text) || string.IsNullOrWhiteSpace(txt_oprice.Text) || string.IsNullOrWhiteSpace(txt_disc.Text))
{
lbl_incorrect.Visible = true;
}
else
{
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Pizza Mania;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.Parameters.Add(new SqlParameter("#Date", dateTimePicker1.Value.Date));
cmd.Parameters.AddWithValue("#txt_rdvalue", txt_rdvalue.Text);
cmd.Parameters.AddWithValue("#txt_orderid", Convert.ToDouble(txt_orderid.Text));
cmd.Parameters.AddWithValue("#cb_oname", cb_oname.SelectedItem);
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedItem);
cmd.Parameters.AddWithValue("#cb_oqty", Convert.ToDouble(cb_oqty.SelectedItem));
cmd.Parameters.AddWithValue("#txt_oprice", Convert.ToDouble((txt_oprice.Text)));
cmd.Parameters.AddWithValue("#txt_disc", Convert.ToDouble(txt_disc.Text));
cmd.Parameters.AddWithValue("#txt_orderprice", txt_orderprice.Text);
cmd.Parameters.AddWithValue("#txt_call", txt_call.Text);
if (txt_call.Text == null)
{
cmd.Parameters.AddWithValue(#"txt_call", txt_call.Text == null);
}
cmd.ExecuteNonQuery();// here i am getting the error that the parameterized query cb_' expects the parameter cb_ocat which was not supplied.
//MessageBox.Show("Order Inserted");
con.Close();
}
am not much sure of this but
if cb_oact is string try to convert it to String
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedItem.ToString());
Hope this works

Stored procedure is not working and getting stopped

I m running a piece of code for scheduler in my project. But it is not working as expected.
private void Initiate_User(string strEmpCard)
{
//conn.Open();
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString() + "", conn);
ObjPriCmd.ExecuteNonQuery();
}
The debugger stops and opens a form after my ExecuteNonQuery() line is debugged. I am not able to trace the error also. what is wrong here ??
UPDATE
My error query
insert into p_emp_clearance_hdr
(Emp_mkey,
Emp_card_no,
RA_1,
RA_2,
Depatment,
Sub_Department,
Date_of_Joining,
Resignation_date,
Last_Working_Days,
UserId)
select
em.mkey,
em.emp_card_no,
em.Reporting_To,
em.Reporting_To2,
em.Department_mkey,
em.SubDept_mkey,
convert(varchar(10), em.resig_date, 103) resig_date,
convert( varchar(10), em.Dt_Of_Join, 103) Dt_Of_Join,
convert(varchar(10), em.Dt_of_leave, 103) Dt_of_leave,
um.mkey
from emp_mst em join user_mst um
on em.mkey = um.Employee_mkey
where em.mkey = #emp_mkey
As you explained in comments, you are getting error:
ExecuteNonQuery: Connection property has not been initialized.
It means you have not initialized the connection. You have just declared it:
SqlConnection conn;
You should do like:
conn = new SqlConnection(#"you connection string");
//then your code
ObjPriCmd = new SqlCommand("exec [sp_c_Initiate_Clearance] " + strEmpCard.ToString(), conn);
ObjPriCmd.ExecuteNonQuery();
The best practice:
You should use a SqlCommand property CommandType to define that you're calling a StoredProcedure when calling from C#. And define parameters using SqlCommand .Parameters.Add it handles the SqlInjection issues itself.
conn = new SqlConnection(#"you connection string");
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// parameter name , parameter type parameter value
cmd.Parameters.Add("#parameter name", SqlDbType.VarChar).Value = strEmpCard.ToString();
con.Open();
cmd.ExecuteNonQuery();
}
You can Try it with USing Statement:-
using (SqlCommand cmd = new SqlCommand("sp_c_Initiate_Clearance", conn)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Parameter Name", Type).Value = "Value of Parameter";
conn.Open();
cmd.ExecuteNonQuery();
}

insert Empty Textbox value in SQL Server

I have some textbox which can have empty value. When I am trying to insert that textbox.text in insert command then it show error in sql. I want the automatic check when textbox is empty it will insert null in database in sql server 2008 R2. I am using normal insert into command and I do not want to use procedure(too clumsy).
please help me anyone.
Thanks in advance.
Not really sure about your code, but it should be like:
using (SqlConnection conn = new SqlConnection("ConnectionString"))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "INSERT into yourTable(ID, Col1, Col2) VALUES (#ID, #Col1, #Col2);";
cmd.Connection = conn;
conn.Open();
cmd.Parameters.AddWithValue("#ID", yourID);
cmd.Parameters.AddWithValue("#Col1", string.IsNullOrWhiteSpace(textBox1.Text) ?
DBNull.Value: textBox1.Text);
cmd.Parameters.AddWithValue("#Col2", string.IsNullOrWhiteSpace(textBox2.Text) ?
DBNull.Value : textBox2.Text);
cmd.ExecuteNonQuery();
}
You can check for Empty String using string.IsNullOrWhiteSpace, pass null accordingly. Use string.IsNullOrEmpty(), if you want to consider spaces as valid values.
If you are using direct insert query
"insert into table_name (column1,column2,column3) values("+column1value+","+column2value+","+textbox.Text.Trim()!=""?textbox.Text.Trim():DBNull.Value+")";
Even if you are using parameterised query, you can use the same expression
textbox.Text.Trim()!=""?textbox.Text.Trim():DBNull.Value
Try something like this:
using (SqlConnection conn = new SqlConnecction(connStr))
{
conn.Open();
string qry = "INSERT TargetTable (TargetColumn) VALUES (#TextValue)";
using (SqlCommand cmd = new SqlCommand(qry, conn))
{
cmd.Parameters.Add(new SqlParameter("#TextValue", String.IsNullOrEmptyOrWhiteSpace(textBox.Text) ? DBNull.Value : textBox.Text));
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException sex)
{
// whatever
}
}
}

ASP.net why are these queries not executing?

In my code neither of these queries appear to be running. The debug label is printing as "end" so it is executing something inside that code block, just appears it doesn't like the queries?
// Check input is all valid
if (Page.IsValid)
{
debug.Text = "begin";
using (SqlConnection cn = new SqlConnection(
ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand(
"UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand(
"INSERT INTO tblSiteSettings (allowProductRatings, allowComments, " +
"siteName, settingDate, isActive) VALUES (#allowRatings, " +
"#allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cn.Close();
}
debug.Text = "end";
}
}
A few questions:
Why are they not executing?
In classic ASP for inserts, updates and deletes I would use con.Execute(query) as supposed to using a recordset, am I running my update statement correctly here?
Is my design of the queries good, or should I be executing them in a different manner?
The reason it's not doing anything is because you're not actually executing the queries. What you need to do is:
// Verify that username is unique
using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0", cn))
{
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
using (SqlCommand cmd = new SqlCommand("INSERT INTO tblSiteSettings (allowProductRatings, allowComments, siteName, settingDate, isActive) VALUES (#allowRatings, #allowcomments, #siteName, getDate(), 1)", cn))
{
cmd.Parameters.Add("#allowRatings", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#allowcomments", SqlDbType.Bit).Value = 1;
cmd.Parameters.Add("#siteName", SqlDbType.VarChar, 128).Value = "lol";
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
It's the line cmd.ExecuteNoneQuery(); that you're missing. There are various different Execute methods exposed by the SqlCommand class, the most commonly used are:
ExecuteNonQuery: Executes a query and returns no result from the query (it does return the rows affected as its return value however)
ExecuteScalar: Executes a query and returns the value in the first column of the first row
ExecuteReader: Executes a query and returns the data to a SqlDataReader
Your are missing
cmd.ExecuteScalar();
You may also reuse you SqlConnection, you can open the connection right after the using (SqlConnection cn = new Sql... statement. You don't have to close the connection when the SqlConnection is in a using block, accordning to the documentation the connection is closed when you are leaving the using block.

Categories

Resources