我想把listView1中记录插入数据库,插入前先看数据库中是否有该项记录,有则不插入,没有则插入,我代码如下,但是运行时不报错,也不执行,请各位帮忙看下
foreach (ListViewItem item in listView1.Items)
 {string insertstring = "insert into table1 values('" + item.SubItems[0].Text + "','" + item.SubItems[1].Text + "')";
string connectstring=......//连接数据库字符串
string selectstring1 = "select * from table1 where ID='" + item.SubItems[0].Text + "'and name='" + item.SubItems[1].Text + "'";
DataTable dt= db.selsave(connectstring,selectstring1);
for (int i=0;i<dt.Rows.Count;i++)
{ string a=dt.Rows[i]["name"].ToString();//将name记录赋给a
  if (a != item.SubItems[1].Text)//如果a不等于listView1,则插入记录
{insert(connectstring, insertstring);}

解决方案 »

  1.   

    http://blog.csdn.net/avoid/article/details/3238570
      

  2.   

    string selectstring1 = "select * from table1 where ID='" + item.SubItems[0].Text + "'and name='" + 
    这个ID应该是数据库生成的吧,还能在外面输入?你应该指查找 name ='' 来判断是否重复吧。另外,这种外部查找的方法是有问题的,如果你的页面点击量高,那么可能出现冲突,导致数据库里面重复,所以最好方法是数据库加唯一索引,判断插入异常;或者把查找和输入都放入存储过程里。
      

  3.   

    1. 首先你要确定你的数据库操作代码是能够正常工作和返回数据的,这你可以做个简单的例子测试一下
    2. 你的逻辑好像有问题
       for (int i=0;i<dt.Rows.Count;i++)
       { 
         string a=dt.Rows[i]["name"].ToString();//将name记录赋给a
         if (a != item.SubItems[1].Text)//如果a不等于listView1,则插入记录   逻辑有问题,你必须遍历完dt里所有的rows才能确定数据库中没有重复数据,然后再插入。而你的判断只是一条记录
       
      

  4.   

    写入触发器create trigger My_Insert on 表
    for insert of inserted
    as
    begin
        --取出要插入的数据,在数据库里面进行判断 如果没有则执行插入如果有了就什么也不执行
         --判断方法用     if not exists(select XX,XX,XX,XX,XX,XX from 表 where 条件(这个条件是判断你不重复的数据))
           begin
                  //存入数据
           end
    end
      

  5.   

    更正:for insert of inserted -->for inserted of insert
      

  6.   

    解决了,改成
    string a="";
    for (int i=0;i<dt.Rows.Count;i++)
      {  
       a=dt.Rows[i]["name"].ToString();//将name记录赋给a
      }
    if (a != item.SubItems[0].Text)
     {......}
    非常感谢!
      

  7.   


                String strSql = String.Empty;
                foreach (ListViewItem item in listView1.Items)
                {
                    strSql = String.Format("if not exists(select * from table1 where ID='{0}' and [name]='{1}') insert into table1(ID,[name]) values('{0}','{1}')", item.SubItems[0].Text, item.SubItems[1].Text);
                    insert(connectstring, strSql); //执行数据库添加操作
                }
      

  8.   

    个人觉得逻辑应该修改如下:
    string a="";
    bool flag=true;
    for (int i=0;i<dt.Rows.Count;i++)
    {   
      a=dt.Rows[i]["name"].ToString();//将name记录赋给a
      if(a==item.SubItems[0].Text)
      {
        flag=false;
      }
    }
    if (flag)
     {......}