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"
Related
My query will execute the first time in a switch case loop, but during the second case nothing happens with it
everything is written inside of a for loop, it manages to add the first query into the database properly but after that it doesn't
string sQuery = string.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}',{10}", sName, sMiddleName, sSurname, sBirthdate, sSex, sNationality, sDateOfArrival, sCardID, sUsername, sPassword, sPhoneNumber);
SqlConnection cnn;
cnn = new SqlConnection(Globals.sqlConnect);
cnn.Open();
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
for (int i = 0; i < 2; i++)
{
switch (i)
{
case 0:
sql = "INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES(" + sQuery + ")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
break;
case 1:
if (Properties.Settings.Default.HoF == true)
{
sQuery = string.Format("'{0}' ,{1}",Properties.Settings.Default.Familyname,tb_cardID);
sql = "INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES ("+ sQuery +")";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = command;
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
}
break;
Since I didn't know where the values for the parameters came from I just assumed they were passed into the procedure. You need to check the datatypes of the of the parameters in your database and change the code accordingly. Convert the values to matching types. using blocks ensure that your database objects are closed and disposed even if there is an error. Using parameters protects you form Sql injection.
The loop ,switch and dataadapter are unnecessary.
private void OPCode(string sName,string sMiddleName,string sSurname,DateTime sBirthdate,string sSex,string sNationality,DateTime sDateOfArrival,int sCardID,string sUsername,string sPassword,string sPhoneNumber, int tb_cardID)
{
using (SqlConnection cnn = new SqlConnection(Globals.sqlConnect))
{
using (SqlCommand command = new SqlCommand("INSERT INTO dbo.Refugee ([Name],[Middlename],[Surname],[Birthdate],[Sex],[Nationality],[Date_of_arrival],[ID_Card_Number],[Username],[Password],[Phone_Number]) VALUES (#sName, #sMiddleName, #sSurname, #sBirthdate, #sSex, #sNationality, #sDateOfArrival, #sCardID, #sUsername, #sPassword, #sPhoneNumber);", cnn))
{
command.Parameters.Add("#sName", SqlDbType.VarChar).Value = sName;
command.Parameters.Add("#sMiddleName", SqlDbType.VarChar).Value = sMiddleName;
command.Parameters.Add("#sSurname", SqlDbType.VarChar).Value = sSurname;
command.Parameters.Add("#sBirthdate", SqlDbType.DateTime).Value = sBirthdate;
command.Parameters.Add("#sSex", SqlDbType.VarChar).Value = sSex;
command.Parameters.Add("#sNationality", SqlDbType.VarChar).Value = sNationality;
command.Parameters.Add("#sDateOfArrival", SqlDbType.DateTime).Value = sDateOfArrival;
command.Parameters.Add("#sCardID", SqlDbType.Int).Value = sCardID;
command.Parameters.Add("#sUsername", SqlDbType.VarChar).Value = sUsername;
command.Parameters.Add("#sPassword", SqlDbType.VarChar).Value = sPassword;
command.Parameters.Add("#sPhoneNumber", SqlDbType.VarChar).Value = sPhoneNumber;
cnn.Open();
command.ExecuteNonQuery();
} //disposes command
if (Properties.Settings.Default.HoF == true)
{
using(SqlCommand command = new SqlCommand("INSERT INTO dbo.Family ([Family_name],[Head_Of_Family_ID_Card_Number]) VALUES (#FamilyName, #tb_carID;", cnn))
{
command.Parameters.Add("#Familyname", SqlDbType.VarChar).Value = Properties.Settings.Default.Familyname;
command.Parameters.Add("#tb_cardID", SqlDbType.Int).Value = tb_cardID;
command.ExecuteNonQuery();
}//disposes second command
}
}//closes and disposes connection
}
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.
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;
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 a label for that i have to assign object value which is returned by stored procedure.my code as following
object returnvalue;
SqlConnection con = new SqlConnection("Data Source=vela21; Initial Catalog=MilkDb;Integrated Security=True");
con.Open();
string sa;
sa = textBox1.Text;
SqlCommand cmd = new SqlCommand("custname", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("Cid", SqlDbType.Int).Value = sa;
cmd.Parameters.Add("cname", SqlDbType.NVarChar, 20);
cmd.Parameters["cname"].Direction = ParameterDirection.Output;
returnvalue = cmd.ExecuteNonQuery();
label3.Text = Convert.ToString(returnvalue);
con.Close();
can anyone help me? plz........
label3.Text = Convert.ToString(cmd.Parameters["cname"].Value);
Yeah. Andrey is right...
I had the same answer...
label3.Text = Convert.ToString(cmd.Parameters["cname"].Value);