拆分并更新数据库中的字符串

时间:2017-02-10 12:51:35

标签: asp.net vb.net

我的文本框中有一组字符串,每个字符串用逗号分隔。我想拆分它们并在db中为分割中的每个字符串更新它们的记录。在运行我的代码后,它只更新第一个字符串并保留其余字符串。这是我的代码。

Dim serialnumberlist = Split(txtserial.Text, ",").ToList
For Each serial As String In serialnumberlist 
    'update their branches
    Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString

    Using con As New SqlConnection(constr)
        con.Open()
        Using cmd As New SqlCommand()
            cmd.CommandText = "Update scratchcards set branches=@branches where Pin_Serial=@serial"
            cmd.Parameters.AddWithValue("@branches", ddlbranches.SelectedValue)
            cmd.Parameters.AddWithValue("@serial", serial)
            cmd.Connection = con
            cmd.ExecuteNonQuery()
        End Using
    End Using
Next
Response.Write("<script>alert('Branches allocated successfully!');</script>")

3 个答案:

答案 0 :(得分:3)

除了某种低效率之外,您的代码似乎没有任何问题。输入可能是空的,还是包含连续的分隔符?您可以使用String.Split(Char(), StringSplitOptions)StringSplitOptions.RemoveEmptyEntries来避免这种混淆,这将删除空条目。

如果您怀疑字符串中可能有多个分隔符,例如空格 - 逗号,则可以在separators数组中添加更多分隔符。

正如其他人所评论的那样,您不应该在每次迭代中重建连接和命令。您的代码应更改为:

Dim separators() As String = {","}
Dim serialnumberlist = txtserial.Text.Split(separators,StringSplitOptions.RemoveEmptyEntries)
'update their branches
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString

Using con As New SqlConnection(constr)
    Using cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandText = "Update scratchcards set branches=@branches where Pin_Serial=@serial"
        cmd.Parameters.Add("@branches", SqlDbType.Int)
        cmd.Parameters.Add("@serial", SqlDbType.NVarChar,30)                

        'At the moment of execution
        cmd.Parameters("@branches").Value=ddlbranches.SelectedValue
        con.Open()
        For Each serial As String In serialnumberlist 
            cmd.Parameters("@serial").Value=serial
            cmd.ExecuteNonQuery()
        Next
    End Using
End Using

Response.Write("<script>alert('Branches allocated successfully!');</script>")

每次迭代只需更改参数值。 分割后你不需要调用.ToList() For Each适用于任何IEnumerable

您可以提前创建命令,甚至将其存储在字段中以便重复使用。您只需要为每次执行设置一个新的Connection

<强>更新

从评论中看来,输入数据似乎同时包含逗号空格,即PA/3/0000001740, PA/1/0000004583, PA/4/0000000095。要拆分它,应使用分隔符字符串,,即:

Dim separators() As String = {", "}

如果任何机会在没有空格的情况下启动列,则separators数组应包含两个字符,即:

Dim separators() As String = {",", " "}

Dim separators() As String = {", ",","}

<强>性能

最后,如果只执行一个查询,即UPDATE ... WHERE Pin_Serial in (....),则可以实现此更新的最佳性能。这是有风险的,因为IN表达式不能接受参数。如果序列号是数字,则可以验证输入并加入键。但是,对于文本,意外值可能会产生问题。

在这种情况下,可以修改查询以使用table-valued parameter。但这有点复杂,需要在数据库中创建一个表类型:

CREATE TYPE dbo.PinTableType AS TABLE ( Pin_Serial nvarchar(50) )  

一旦完成,循环可以成为单个查询:

UPDATE scratchcards
set branches=@branches
from scratchcards inner join @serialsTable on myTable.Pin_Serial=scratchcards.Pin_Serial

@serialsTable参数必须是DataTable类型。我会作弊并使用MoreLinqToDataTable()

cmd.CommandText = "UPDATE scratchcards
set branches=@branches
from scratchcards inner join @serialsTable on myTable.Pin_Serial=scratchcards.Pin_Serial"
cmd.Parameters.Add("@branches", SqlDbType.Int)    
cmd.Parameters.Add("@serialsTable",SqlDbType.Structured)

'At the moment of execution
cmd.Parameters("@branches").Value =ddlbranches.SelectedValue
Dim table as DataTable = serialnumberlist.ToDataTable()
cmd.Parameters("@serialsTable").Value=table
cmd.ExecuteNonQuery

答案 1 :(得分:0)

就像我想的那样,它的逗号空间......要么分开&#34;,&#34;或者更好,使用修剪功能

Dim serialnumberlist = Split(txtserial.Text, ",").ToList
For Each serial As String In serialnumberlist 
'update their branches
Dim constr As String = ConfigurationManager.ConnectionStrings("connectionstring").ConnectionString

Using con As New SqlConnection(constr)
    con.Open()
    Using cmd As New SqlCommand()
      cmd.Connection = con  
      cmd.CommandText = "Update scratchcards set branches=@branches where Pin_Serial=@serial"
      cmd.Parameters.AddWithValue("@branches", ddlbranches.SelectedValue)
      cmd.Paramaters.Add("@Serial", SqlDbType.Text)
      For Each serial As String In serialnumberlist
            cmd.Parameters("@Serial").Value = Trim(serial) '<--------HERE
            cmd.ExecuteNonQuery()
      Next       
   End Using
End Using

Response.Write("<script>alert('Branches allocated successfully!');</script>")

答案 2 :(得分:-1)

请尝试这种方式:

Dim serialnumberlist As String() = txtserial.Text.Split(","C)
For Each item As String In serialnumberlist 
    Using con As New SqlConnection("")
        Using cmd As New SqlCommand("Update scratchcards set branches=@branches where Pin_Serial=@serial", con)
            cmd.CommandType = CommandType.StoredProcedure
            cmd.Parameters.AddWithValue("@branches", ddlbranches.SelectedValue)
            cmd.Parameters.AddWithValue("@serial", item )


            cmd.ExecuteNonQuery()
        End Using
    End Using
Next