如果您有多行数据,在一次调用存储过程中一次插入所有行会更加高效。要做到这一点,你将数据序列化到XML中,然后调用一个存储过程,该过程将xml作为字符串参数。
AFAIK你不能序列化字典,但你可以序列化一个列表。
所以我建议你循环你的词典(列表词典)填充一个列表适当的值。我倾向于使用结构这一点,但简单的类做工精细,以及,例如:
Public Class DBData
Public pKey As Integer
Public pValue As Double
Public Sub New(key As Integer, val As Double)
pKey = key
pValue = val
End Sub
Public Sub New()
pKey = 0
pValue = 0.0
End Sub
End Class
创建列表并填写如G:
Dim myList As New List(Of DBData)
For Each kvPair In dict
myList.Add(New DBData(kvPair.Key, kvPair.Value))
Next
现在对于魔术的位序列化:这里
Dim sw As New StringWriter
Dim serializer As New XmlSerializer(GetType(List(Of DBData)))
Dim ns As New XmlSerializerNamespaces()
serializer.Serialize(sw, myList)
Dim xml As String
xml = sw.ToString
Dim pos As Integer
pos = xml.IndexOf("<Array")
xml = xml.Substring(pos)
通知我剥离刚刚创建的XML的头。那是因为如果包含头文件,我从来没有能够使SQL Server工作 - 你可能可以,我从来没有看过够难。
我们这样调用存储过程(显然连接字符串更改为适合您):
Using conn As New SqlConnection("Integrated Security=true; Initial Catalog=dbname; Data Source=servername")
Using cmd As New SqlCommand("uspDBDataInsert", conn)
cmd.CommandType = CommandType.StoredProcedure
Dim param As SqlParameter
param = cmd.CreateParameter
param.ParameterName = "@dbdata"
param.DbType = DbType.String
param.Value = xml
cmd.Parameters.Add(param)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
对于SQL Server中的过程需要看起来像这样:
CREATE PROCEDURE [dbo].[uspDBDataInsert]
-- Add the parameters for the stored procedure here
@dbdata varchar(MAX)
AS
BEGIN try
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @idoc int
--Create an internal representation of the XML document
EXEC sp_xml_preparedocument @idoc OUTPUT, @dbdata
insert into DBData
(
id, rowvalue
)
select
pKey,pValue
FROM OPENXML (@idoc, '/ArrayOfDBData/DBData',2)
WITH (
pKey int,
pValue float
)
select @@ROWCOUNT
end try
begin catch
declare @msg nvarchar(200)
SELECT @msg = ('Error during insert of DBData...')
end catch
显然,在这里你需要将ArrayOf更改为你所称的类,当然也可以使用你自己的表。
虽然我在这里展示了一个简单的键/值对,但您可以用完全相同的方式填充多列表。
需要注意的一点:您的类/结构必须在Public模块中为Public,否则序列化将不起作用。同样,如果你为类提供你自己的参数构造函数(就像我一样),你还必须提供一个无参数的参数,否则序列化程序会反对。
HTH
附录
什么我忘了,对于VB工作,你需要:
Imports System.IO
Imports System.Xml.Serialization
Imports System.Data.SqlClient
但这将仅仅只有进入TEST6测试1 ...我需要它从Excel工作表中输入多行数据到数据库中。我知道它很简单,但只是让它在我的脑海中变得更加难以实现。 – user3013325
好的,我明白你的意思了,坚持下去。 – NickyvV