本文介绍了我想检查此代码n给我解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望列表框值存储在sql数据库中.所以我有代码.

Hi, I want the List Box values stored in the sql database. So I have code.

Dim DR As SqlDataReader
Dim con As SqlConnection
Dim cmd As SqlCommand
con = New SqlConnection("Data Source=LOCALhost;Initial Catalog=InwardOutwardSystem;Integrated Security=True")
con.Open()
Dim l As String
Dim i As Integer

For i = 0 To ListBox1.Items.Count Step 1
   l = "insert into TransactionCirculation(ForUserId)values('" & ListBox1.Items(i) & "')"
   cmd = New SqlCommand(l, con)
Next

DR = cmd.ExecuteReader(CommandBehavior.CloseConnection)
MsgBox("Data is successfully saved")


这段代码在vb.net中.在这种情况下,我使用for下一个循环,但条件条件行中出现"for"错误.请给我建议.谢谢.


This code is in vb.net. In this I''m use the for next loop, but have a error in "for" condition line. Please give me suggestions. Thanks.

推荐答案

For i = 0 To ListBox1.Items.Count - 1 Step 1

相反.


Dim query  As String
For Each item As String In listBox1.Items
     query   = "insert into TransactionCirculation(ForUserId)values('" & item  & "')"
     cmd = New SqlCommand(query  , con)

Next



您需要使用executenonquery方法,而不是ExecuteReader,并且还需要为每个项目运行
executenonquery,表示在循环内运行executenonquery. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx [ ^ ]



you need to use executenonquery method, not the ExecuteReader, and also for each item you need to run
executenonquery, that means run executenonquery inside the loop. http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx[^]


INSERT INTO Table(column)
SELECT ListItemOne
UNION ALL
SELECT ListItemTwo
UNION ALL
etc.


您可能需要修改循环以构建这样的SQL语句,但最终结果是一次调用数据库,而不是多次调用.


You would need to modify your loop to build a SQL statement like this, but the end result is one call to the database instead of multiple.


这篇关于我想检查此代码n给我解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 11:51