2012-08-11 81 views
0

我想將字符串數組作爲SQL參數傳遞,但是當我執行該命令時,它會拋出一個異常,指出「對象必須實現IConvertible」。這裏是代碼(所有三列是nvarchar的):無法將SQL參數值設置爲字符串數組

Public Sub sendsms(messageBodies As String(), ByVal recipientNumbers As String(), Optional ByVal chkMsgIds As string() = Nothing) 
    Dim con As New SqlConnection 
    con.ConnectionString = connection.Sms 
    Dim cmd As New SqlCommand("insert into sentmessage (text,id,number) values (@text,@id,@number)", con) 
    cmd.Parameters.Add("@text", Data.SqlDbType.NVarChar, n).Value = messageBodies 
    cmd.Parameters.Add("@id", Data.SqlDbType.NVarChar, n).Value = chkMsgIds 
    cmd.Parameters.Add("@number", Data.SqlDbType.NVarChar, n).Value = recipientNumbers 
    con.Open() 
    cmd.ExecuteNonQuery() 
    con.Close() 
    cmd.Dispose() 
End Sub 

我創造了這個程序中插入的記錄大量到數據庫中,什麼是正確的做法?

+0

你預期會發生什麼?你是否希望將數組的所有元素合併爲一個單獨的行字符串,或者用逗號分隔,還是將其製作爲每行含有一個數組項的多行字符串? – 2012-08-11 11:12:15

+0

我應該如何插入大量的記錄到sql? – 2012-08-11 11:19:26

回答

0

通常情況下,你只需執行多個INSERT命令,每行一個,如:

Public Sub sendsms(messageBodies As String(), ByVal recipientNumbers As String(), Optional ByVal chkMsgIds As string() = Nothing) 
    Using con As New SqlConnection() 
     con.ConnectionString = connection.Sms 
     con.Open() 
     For Each body As String In messageBodies 
      Using cmd As New SqlCommand("insert into sentmessage (text,id,number) values (@text,@id,@number)", con) 
       cmd.Parameters.Add("@text", Data.SqlDbType.NVarChar, n).Value = body 
       cmd.Parameters.Add("@id", Data.SqlDbType.NVarChar, n).Value = chkMsgIds 
       cmd.Parameters.Add("@number", Data.SqlDbType.NVarChar, n).Value = recipientNumbers 
       cmd.ExecuteNonQuery() 
      End Using 
     Next 
    End Using 
End Sub 

然而,在SQL Server 2008中,他們增加了其在這裏說明一個新的多行插入語法的支持:

http://blog.sqlauthority.com/2008/07/02/sql-server-2008-insert-multiple-records-using-one-insert-statement-use-of-row-constructor/

例如,您可以執行的命令,例如:

insert into sentmessage (text,id,number) values 
('First',1,1), 
('Second',2,2), 
('Third',3,3) 
+0

感謝您在德黑蘭炎熱的下午提供幫助。 – 2012-08-11 11:47:59

0

只是使用:

cmd.Parameters.AddWithValue("@text", messageBodies) 
cmd.Parameters.AddWithValue("@id",chkMsgIds) 
cmd.Parameters.AddWithValue("@number", recipientNumbers) 
相關問題