This is basically a method to insert a record into a table. It was working fine before I decided to add in a way to check if the Customer ID already exists in the database. I get a
'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Procedure or function InsertCustomer has too many arguments specified.
on the line
command.ExecuteNonQuery();
I don't understand what's wrong.
public void add()
{
lblMessage.Text = "";
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CheckDetails";
command.Parameters.AddWithValue("#CustID", txtCID.Text);
conn.Open();
int check = (int)command.ExecuteScalar();
if (check == 0)
{
command.CommandText = "InsertCustomer";
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
command.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFName.Text;
command.Parameters.Add("#Surname", SqlDbType.VarChar).Value = txtLName.Text;
command.Parameters.Add("#Gender", SqlDbType.VarChar).Value = rdoGender.Text;
command.Parameters.Add("#Age", SqlDbType.Int).Value = txtAge.Text;
command.Parameters.Add("#Address1", SqlDbType.VarChar).Value = txtAdd1.Text;
command.Parameters.Add("#Address2", SqlDbType.VarChar).Value = txtAdd2.Text;
command.Parameters.Add("#City", SqlDbType.VarChar).Value = txtCity.Text;
command.Parameters.Add("#Phone", SqlDbType.VarChar).Value = txtPhone.Text;
command.Parameters.Add("#Mobile", SqlDbType.VarChar).Value = txtMobile.Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtEmail.Text;
command.ExecuteNonQuery();
lblMessage.Text = "Customer Details Added.";
}
else
{
lblMessage.Text = "Customer ID already exists.";
}
conn.Close();
}
You are adding the same parameter twice:
command.Parameters.AddWithValue("#CustID", txtCID.Text);
// ....
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
You can use command.Parameters.Clear();. But i'd prefer to use two different SqlCommands for the two procedures CheckDetails and InsertCustomer to avoid such issues.
Side-note: don't let the database try-cast the value for you. Use int.TryParse.
Remove below parameter from your statement, you already add parameter in command:
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
Related
it always show an error Incorrect syntax near ')'.
I didnt see any wrong inputs
See my code below
byte[] content = ImageToStream(fName);
cnn.Open();
string sql = "update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id)";
SqlCommand cmd1 = new SqlCommand(sql, cnn);
cmd1.Parameters.AddWithValue("#pic", SqlDbType.Image).Value = content;
cmd1.Parameters.AddWithValue("#fname", SqlDbType.VarChar).Value = txtfirstname.Text;
cmd1.Parameters.AddWithValue("#mname", SqlDbType.VarChar).Value = textBox1.Text;
cmd1.Parameters.AddWithValue("#lname", SqlDbType.VarChar).Value = txtlastname.Text;
cmd1.Parameters.AddWithValue("#position", SqlDbType.VarChar).Value = comboBox2.Text;
cmd1.Parameters.AddWithValue("#startterm", SqlDbType.DateTime).Value = dateTimePicker2.Value.Date;
cmd1.Parameters.AddWithValue("#endterm", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
cmd1.Parameters.AddWithValue("#id", SqlDbType.Int).Value = int.Parse(ID.Text);
cmd1.ExecuteNonQuery();
cnn.Close();
MessageBox.Show("successfully updated");
dataGridView1.DataSource = db.sp_viewofficials();
it should save to sql server my save works
Your update statement has extra ending bracket which is not needed.
"update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id"
I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.
I'm trying to insert something into a SQL server (using c#) and when I try to it says it requires the (in the query) given parameter and that it can't find it while it is declared.
"Additional information: The parameterized query '(#art varchar(8000),#oms varchar(8000),#rem varchar(8000),#artdk' expects the parameter '#art', which was not supplied."
I checked parameter amount, the database connection and I tried to use another insert command I have as reference but I couldn't get it to work. and I couldn't find the same sort of problem on the internet yet. if someone could help me, it would be much appreciated.
UPDATE:
I changed the artnr.selectedvalue to artnr.text and that sort of got me some progress but now I get this error
UPDATE2:
seems that if I fill every box it tries to insert it works.. yet it does allow null in all database cell's so the issue has been found. just got to work out which one('s) cant have empty.
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Error converting data type varchar to numeric.
it gives this error when I put in all numeric or all text
SqlCommand slinkoopadd = new SqlCommand(#"insert into ART (ART ,OMS ,REM ,ARTDK ,TYPE ,MAG ,PROGRAM ,EH1 ,LEV ,LTD ,INK ,KOR ,SGR ,EH2 ,EF ,VALUTA ,CRNI )
values (#art,#oms,#rem,#artdk,#type,#mag,#program,#eh1,#lev,#ltd,#ink,#kor,#sgr,#eh2,#ef,#valuta,#crni);", Connectie.connMEVO_ART);
#region parameters
slinkoopadd.Parameters.Add("#art", SqlDbType.VarChar).Value = this.artnr.SelectedValue;
slinkoopadd.Parameters.Add("#oms", SqlDbType.VarChar).Value = this.tekstinkoopoms.Text;
slinkoopadd.Parameters.Add("#rem", SqlDbType.VarChar).Value = this.tekstinkoopopmerk.Text;
slinkoopadd.Parameters.Add("#artdk", SqlDbType.VarChar).Value = this.tekstinkoopnummerlev.Text;
slinkoopadd.Parameters.Add("#type", SqlDbType.VarChar).Value = this.tekstinkooparttype.Text;
slinkoopadd.Parameters.Add("#mag", SqlDbType.VarChar).Value = this.tekstinkoopmagazijnloc.Text;
slinkoopadd.Parameters.Add("#program", SqlDbType.VarChar).Value = this.tekstinkoopinternopmerk.Text;
slinkoopadd.Parameters.Add("#eh1", SqlDbType.VarChar).Value = this.tekstinkoopeenheid.Text;
slinkoopadd.Parameters.Add("#lev", SqlDbType.VarChar).Value = this.tekstinkoopstandleveran.Text;
slinkoopadd.Parameters.Add("#ltd", SqlDbType.VarChar).Value = this.tekstinkooplevertijd.Text;
slinkoopadd.Parameters.Add("#ink", SqlDbType.VarChar).Value = this.tekstinkoopbrutoprijs.Text;
slinkoopadd.Parameters.Add("#kor", SqlDbType.VarChar).Value = this.tekstinkoopkorting.Text;
slinkoopadd.Parameters.Add("#sgr", SqlDbType.VarChar).Value = this.tekstinkoopserievoorraad.Text;
slinkoopadd.Parameters.Add("#eh2", SqlDbType.VarChar).Value = this.tekstinkoopgebruikeh.Text;
slinkoopadd.Parameters.Add("#ef", SqlDbType.VarChar).Value = this.textinkoopehfactor.Text;
//slinkoopadd.Parameters.Add("#", SqlDbType.VarChar).Value = this.artnr.Text;//perc. voor vracht
slinkoopadd.Parameters.Add("#valuta", SqlDbType.VarChar).Value = this.tekstinkoopvaluta.Text;
slinkoopadd.Parameters.Add("#crni", SqlDbType.VarChar).Value = this.tekstinkoopcrni.Text;
//slinkoopadd.Parameters.Add("#", SqlDbType.VarChar).Value = this.artnr.Text;//extra kosten
//slinkoopadd.Parameters.Add("#", SqlDbType.VarChar).Value = this.artnr.Text;//bestelgrootte afroep
//slinkoopadd.Parameters.Add("#", SqlDbType.VarChar).Value = this.artnr.Text;//prognose jaarverbruik
//slinkoopadd.Parameters.Add("#", SqlDbType.VarChar).Value = this.artnr.Text;//levertijd nieuwe afr
#endregion
drART = slinkoopadd.ExecuteReader();
MessageBox.Show("Opgeslagen!");
fillbox();
while (drART.Read())
{ }
slinkoopadd.Dispose();
Try it like this?
slinkoopadd.Parameters.Add("#art", SqlDbType.VarChar);
slinkoopadd.Parameters["#art"].Value = this.artnr.SelectedValue;
I'm not sure you can pipe the call like that.
drART = slinkoopadd.ExecuteReader();
You don't expect to read something. You want to insert, that is not a query:
var result = slinkoopadd.ExecuteNonQuery();
i changed some small things in the query and i made sure some of the textboxes get a default value if it doesnt have anything in it so now it works. this is the current query that works.
if (tekstinkoopcrni.Text == "1") { } else if (tekstinkoopcrni.Text == "0") { }
else { tekstinkoopcrni.Text = "0"; }
if (tekstinkoopkorting.Text == "") { tekstinkoopkorting.Text = "0"; }
if (tekstinkoopserievoorraad.Text == "") { tekstinkoopserievoorraad.Text = "0"; }
if (tekstinkoopstandleveran.Text == "") { tekstinkoopstandleveran.Text = "9999"; }
if (tekstinkooplevertijd.Text == "") { tekstinkooplevertijd.Text = "0"; }
SqlCommand slinkoopadd = new SqlCommand(#"insert into ART (ART ,OMS ,REM ,ARTDK ,TYPE ,
MAG ,PROGRAM ,EH1 ,INK ,KOR ,SGR ,EH2 ,EF ,VALUTA ,CRNI ,LEV ,LTD )
values (#art,#oms,#rem,#artdk,#type,#mag,#program,#eh1,#ink,#kor,#sgr,#eh2,#ef,
#valuta,#crni, #lev,#ltd);", Connectie.connMEVO_ART);
#region parameters
slinkoopadd.Parameters.Add("#art", SqlDbType.VarChar).Value = this.artnr.Text;
slinkoopadd.Parameters.Add("#oms", SqlDbType.VarChar).Value = this.tekstinkoopoms.Text;
slinkoopadd.Parameters.Add("#rem", SqlDbType.VarChar).Value = this.tekstinkoopopmerk.Text;
slinkoopadd.Parameters.Add("#artdk", SqlDbType.VarChar).Value = this.tekstinkoopnummerlev.Text;
slinkoopadd.Parameters.Add("#type", SqlDbType.VarChar).Value = this.tekstinkooparttype.Text;
slinkoopadd.Parameters.Add("#mag", SqlDbType.VarChar).Value = this.tekstinkoopmagazijnloc.Text;
slinkoopadd.Parameters.Add("#program", SqlDbType.VarChar).Value = this.tekstinkoopinternopmerk.Text;
slinkoopadd.Parameters.Add("#eh1", SqlDbType.VarChar).Value = this.tekstinkoopeenheid.Text;
slinkoopadd.Parameters.Add("#lev", SqlDbType.VarChar).Value = this.tekstinkoopstandleveran.Text;
slinkoopadd.Parameters.Add("#ltd", SqlDbType.VarChar).Value = this.tekstinkooplevertijd.Text;
slinkoopadd.Parameters.Add("#ink", SqlDbType.VarChar).Value = this.tekstinkoopbrutoprijs.Text;
slinkoopadd.Parameters.Add("#kor", SqlDbType.VarChar).Value = this.tekstinkoopkorting.Text;
slinkoopadd.Parameters.Add("#sgr", SqlDbType.VarChar).Value = this.tekstinkoopserievoorraad.Text;
slinkoopadd.Parameters.Add("#eh2", SqlDbType.VarChar).Value = this.tekstinkoopgebruikeh.Text;
slinkoopadd.Parameters.Add("#ef", SqlDbType.VarChar).Value = this.textinkoopehfactor.Text;
slinkoopadd.Parameters.Add("#valuta", SqlDbType.VarChar).Value = this.tekstinkoopvaluta.Text;
slinkoopadd.Parameters.Add("#crni", SqlDbType.VarChar).Value = this.tekstinkoopcrni.Text;
#endregion
drART = slinkoopadd.ExecuteReader();
MessageBox.Show("Artikel opgeslagen!");
fillbox();
while (drART.Read())
{ }
slinkoopadd.Dispose();
I am having problem with my code Always having the error which i am not understanding. Please help with my code
i want to retrieve the user details from the db for login page
string uname = TextBox1.Text.Trim();
string pass = TextBox2.Text.Trim();
try
{
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
Response.Write("Login successful");
}
else
{
Response.Write("login Unsucessful");
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}
You need to create your cmd prior to adding the paramaters. Your code should look like:
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
EDIT: and as #ekad said, you do not need cmd.ExecuteNonQuery();
I have stored proc as below:
ALTER PROC pr_Update_Users_Nomination
(
#UserID AS VARCHAR(100),
#Nominated AS BIT
)
AS
UPDATE User
SET isNominated = #Nominated
WHERE
EMPID = #UserID;
I want to call this procedure from c# code: Below is the code I am trying:
void OpenConnection()
{
string Nominated = "False";
//Connection String
string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
SqlConnection mySqlCon = new SqlConnection(sConnString);
SqlCommand mySqlCom = mySqlCon.CreateCommand();
//Call the stored proc and provide in parameters
mySqlCom.CommandText = "EXECUTE pr_Update #UserID #Nominated";
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
mySqlCon.Open();
mySqlCom.ExecuteNonQuery();
mySqlCon.Close();
}
I get an error saying
Incorrect Syntax near #Nominated
first, when executing a procedure with parameter(s), separate the parameters with a comma
EXECUTE pr_Update #UserID, #Nominated
second, modify your code into this,
string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
using(SqlConnection mySqlCon = new SqlConnection(sConnString))
{
using(SqlCommand mySqlCom = new SqlCommand())
{
mySqlCom.Connection = mySqlCon;
mySqlCom.CommandText = "pr_Update";
mySqlCom.CommandType = CommandType.StoredProcedure;
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
try
{
mySqlCon.Open();
mySqlCom.ExecuteNonQuery();
}
catch(SqlException ex)
{
// do something with the exception
// don't hide it
}
}
}
You are missing a comma (,) between the parameters.
It should be
mySqlCom.CommandText = "EXECUTE pr_Update #UserID, #Nominated";
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
Alternatively, since all you are doing is calling a stored proc, you could do:
mySqlCom.CommandType = CommandType.StoredProcedure ;
mySqlCom.CommandText = "pr_Update"; //no need to specify parameter names
mySqlCom.Parameters.Add("#UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("#Nominated", SqlDbType.Bit).Value = Nominated;
Give only name of stored procedure, as you are adding parameter in statements after this. Also set CommandType.
mySqlCom.CommandText = "pr_Update";
mySqlCom.CommandType = CommandType.StoredProcedure;
You are invoking wrong SQL. You should set the command text of command to pr_Update only:
mySqlCom.CommandText = "pr_Update";
And set type command type to stored procedure:
mySqlCom.CommandType = CommandType.StoredProcedure;
See MSDN page for more.