SqlCommand cmd = new SqlCommand(sqlstr, con); SqlDataReader sdr = cmd.ExecuteReader(); if (sdr.Read()) { //执行 } else { //不执行 }
完整代码你看一下: int id =3; string constr = ConfigurationManager.AppSettings["cn"].ToString(); SqlConnection con = new SqlConnection(constr); con.Open(); if (CheckBox2.Checked == true) { string sqlstr = "select * from ym where id= ' " + id + "'and name ='" + CheckBox2.Text.ToString().Trim() + "'"; SqlCommand cmd = new SqlCommand(sqlstr, con); SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read()) { string sqlstr1 = "insert ym (fid,name,id)values('" + 10001 + "','" + CheckBox2.Text.ToString().Trim() + "','" + id + "')"; SqlCommand cmd1 = new SqlCommand(sqlstr1, con); } else {
// SqlDataReader sdr1 = cmd.ExecuteReader();
} sdr.Close(); } else { string sqlstr2 = "delete from ym where id= '" + id + "'and name ='" + CheckBox2.Text.ToString().Trim() + "'"; SqlCommand cmd2 = new SqlCommand(sqlstr2, con); SqlDataReader sdr2 = cmd2.ExecuteReader(); } con.Close(); 放上面下面都不行 不知道为什么 没有报错 就是没数据加到数据库
string sqlstr1 = "insert ym (fid,name,id)values('" + 10001 + "','" + CheckBox2.Text.ToString().Trim() + "','" + id + "')"; SqlCommand cmd1 = new SqlCommand(sqlstr1, con); 而且你insert又没执行,我劝你还是去网上找几个SqlCommand的例子看看吧
sdr.Read()这是判断有没有数据的啊,而且你执行了两次,第一条数据给你跳过去了
sdr.Read()这是判断有没有数据的啊,而且你执行了两次,第一条数据给你跳过去了这个要怎么写 有数据就不执行insert ,没数据就执行
SqlCommand cmd = new SqlCommand(sqlstr, con);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
//执行
}
else
{
//不执行
}
int id =3;
string constr = ConfigurationManager.AppSettings["cn"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
if (CheckBox2.Checked == true)
{
string sqlstr = "select * from ym where id= ' " + id + "'and name ='" + CheckBox2.Text.ToString().Trim() + "'";
SqlCommand cmd = new SqlCommand(sqlstr, con);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string sqlstr1 = "insert ym (fid,name,id)values('" + 10001 + "','" + CheckBox2.Text.ToString().Trim() + "','" + id + "')";
SqlCommand cmd1 = new SqlCommand(sqlstr1, con);
}
else
{
// SqlDataReader sdr1 = cmd.ExecuteReader();
}
sdr.Close();
}
else
{
string sqlstr2 = "delete from ym where id= '" + id + "'and name ='" + CheckBox2.Text.ToString().Trim() + "'";
SqlCommand cmd2 = new SqlCommand(sqlstr2, con);
SqlDataReader sdr2 = cmd2.ExecuteReader();
}
con.Close();
放上面下面都不行 不知道为什么 没有报错 就是没数据加到数据库
SqlCommand cmd1 = new SqlCommand(sqlstr1, con);
而且你insert又没执行,我劝你还是去网上找几个SqlCommand的例子看看吧
那就代码反一反呗
那就代码反一反呗
if和else 都放过了 就是不执行好就是 select 做了 上面没数据,然后 if (sdr.Read())这个好像完全没用
把这句加上去 SqlDataReader sdr1 = cmd.ExecuteReader();把上面的这句SqlDataReader sdr = cmd.ExecuteReader();隐藏因为数据库里面id设了主键 当重复加的时候会报错 这个有什么办法让他不报错否 不报错也就成功了
http://bbs.csdn.net/topics/390789802