我想把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);}
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);}
解决方案 »
- 求正则识别字符串格式
- teechart 根据sql server 数据表 画雷达图
- C#中如何判断现在时间属于晚上8:00到早上8:00?
- webbrows控件打包的问题:you must have a license to use the activex control
- datagridview 怎么将第N条显示在顶部 而并不一定是第一条记录
- 怎么样根据文件的扩展名来决定文件的图标?
- 还是菜鸟问题~~ 锯齿型数
- C#连接oracle 出现的版本不同的问题
- 请问如何在子类里引发基类中的一个事件?
- 用api找到一个按扭的句柄后,怎么click它?
- c#和c++
- 关于DataGridView 的问题
这个ID应该是数据库生成的吧,还能在外面输入?你应该指查找 name ='' 来判断是否重复吧。另外,这种外部查找的方法是有问题的,如果你的页面点击量高,那么可能出现冲突,导致数据库里面重复,所以最好方法是数据库加唯一索引,判断插入异常;或者把查找和输入都放入存储过程里。
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才能确定数据库中没有重复数据,然后再插入。而你的判断只是一条记录
for insert of inserted
as
begin
--取出要插入的数据,在数据库里面进行判断 如果没有则执行插入如果有了就什么也不执行
--判断方法用 if not exists(select XX,XX,XX,XX,XX,XX from 表 where 条件(这个条件是判断你不重复的数据))
begin
//存入数据
end
end
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)
{......}
非常感谢!
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); //执行数据库添加操作
}
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)
{......}