sql vb net在for循环中添加记录 [英] sql vb net add records in for loop

查看:60
本文介绍了sql vb net在for循环中添加记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在datagridview中有这个代码 - 1代表循环:

I have this code in a datagridview count - 1 for loop :

for i = 0 to datagridview1.count-1                        
Dim a As String
                        a = "INSERT INTO Table_1(id_2, name, mobile, date_send) VALUES (@id21, @name1, @mobile1, @date_send1)"

                        Dim myCommand = New SqlCommand(a, SqlConnection2)

                        myCommand.Parameters.Add("@id21", SqlDbType.VarChar, 50).Value = v.ToString
                        myCommand.Parameters.Add("@name1", SqlDbType.VarChar, 50).Value = Me.DataGridView1.Rows(i).Cells(1).Value.ToString
                        myCommand.Parameters.Add("@mobile1", SqlDbType.VarChar, 50).Value = o.ToString
                        myCommand.Parameters.Add("@date_send1", SqlDbType.VarChar, 50).Value = Date.Today.ToString
                        SqlConnection2.Open()
                        myCommand.ExecuteNonQuery()
                        SqlConnection2.Close()
next



执行时它只插入循环的第一条记录,我只想发送给e ach datagridview item。


When executed it inserts only the First record of the loop, I just want to send for each datagridview item.

推荐答案

可能这是因为你忘了在循环中增加变量v的值。因此,当第二次转向时,可能会因重复的主键值插入失败而抛出一些异常。

试试这个 -

Probably this is due to you have forgoten to increament value of the variable "v" in the loop. So, when the second turn onwards it might be throwing some exception for duplicate primary key value insert failed.
Try this-
for i = 0 to datagridview1.count-1                        
Dim a As String

                        a = "INSERT INTO Table_1(id_2, name, mobile, date_send) VALUES (@id21, @name1, @mobile1, @date_send1)"
 
                        Dim myCommand = New SqlCommand(a, SqlConnection2)
 
                        myCommand.Parameters.Add("@id21", SqlDbType.VarChar, 50).Value = v.ToString
                        myCommand.Parameters.Add("@name1", SqlDbType.VarChar, 50).Value = Me.DataGridView1.Rows(i).Cells(1).Value.ToString
                        myCommand.Parameters.Add("@mobile1", SqlDbType.VarChar, 50).Value = o.ToString
                        myCommand.Parameters.Add("@date_send1", SqlDbType.VarChar, 50).Value = Date.Today.ToString
                        SqlConnection2.Open()
                        myCommand.ExecuteNonQuery()
                        SqlConnection2.Close()
                        v++; 'this is what you have missed
next





N:B:您可能也错过了更新@ mobile1的价值



希望,它有帮助:)



N:B: You may have also missed to update the value for @mobile1

Hope, it helps :)


这篇关于sql vb net在for循环中添加记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆