Reputation:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
cn.ConnectionString = @"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
cn.Open();
string n = Convert.ToString(txtfid.Text);
cmd.CommandText = "select * from Personal_det where FID=" + n + "";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
da1.SelectCommand = cmd;
da1.Fill(ds1, "Personal_det");
double dn = ds1.Tables["Personal_det"].Rows.Count;
if (dn == 0)
{
DateTime sdt = DateTime.Today;
SqlCommand cmd3 = new SqlCommand();
cn.Close();
cn.Open();
cmd3.CommandText = "insert into Personal_det(FID,Name,DOB,MobileNo,EmailId,add1,add2,add3,Pincode) values(@FID,@Name,@DOB,@MobileNo,@EmailId,@add1,@add2,@add3,@Pincode)";
cmd3.CommandType = CommandType.Text;
cmd3.Connection = cn;
cmd3.Parameters.Add("@FID", SqlDbType.VarChar,50);
cmd3.Parameters["@FID"].Value = this.txtfid.Text;
cmd3.Parameters.Add("@Name", SqlDbType.VarChar, 50);
cmd3.Parameters["@Name"].Value = this.txtname.Text;
cmd3.Parameters.Add("@DOB", SqlDbType.DateTime, 8);
cmd3.Parameters["@DOB"].Value = Convert.ToDateTime(this.txtdob.Text);
cmd3.Parameters.Add("@MobileNo", SqlDbType.Decimal, 18);
cmd3.Parameters["@MobileNo"].Value = this.txtmbl.Text;
cmd3.Parameters.Add("@EmailId", SqlDbType.VarChar, 50);
cmd3.Parameters["@EmailId"].Value = this.txtmail.Text;
cmd3.Parameters.Add("@add1", SqlDbType.VarChar, 50);
cmd3.Parameters["@add1"].Value = this.txtadd1.Text;
cmd3.Parameters.Add("@add2", SqlDbType.VarChar, 50);
cmd3.Parameters["@add2"].Value = this.txtadd2.Text;
cmd3.Parameters.Add("@add3", SqlDbType.VarChar, 50);
cmd3.Parameters["@add3"].Value = this.txtadd3.Text;
cmd3.Parameters.Add("@Pincode", SqlDbType.Decimal, 18);
cmd3.Parameters["@Pincode"].Value = this.txtpin.Text;
cmd3.ExecuteNonQuery();
cn.Close();
This is my C# code..Actually what i have done is previously i had FID as int now i converted it as varchar(50),because of some needs,i have already changed the datatype in sql..Personal_det is the table where in FID is a primary key constraint and foriegn key for other tables..Now When i am going to execute the code..it gives the error shown in the Image
Upvotes: 2
Views: 307
Reputation: 76
Do not create CommandText using strings concatenation - such a bad practice make your sql queries vulnerable for sql-injections. You can use SqlParameter also for "select" queries, like this.
cmd.CommandText = "select * from Personal_det where FID=@fid";
...
cmd.Parameters.Add(new SqlParameter("@fid", fidValue))
Upvotes: 2
Reputation: 63065
since FID
is string you need to use ''
as below
cmd.CommandText = "select * from Personal_det where FID='" + n + "'";
above will avoid your exception but it is not safe
You need to use parameters like you did on second case
Upvotes: 1