生成字母数字ID VB.NET时出错

时间:2018-10-22 08:15:15

标签: mysql vb.net

我试图通过将用户公司+自动生成的ID串联在一起来生成唯一ID。

我的字母数字输出为“ SNC001”,但是当我尝试生成下一个ID时,出现以下错误:

  

从字符串“ SNC001”到类型'Integer'的转换无效。

PS:“ SNC”来自此frm_Main_Menu.lblCompany.Text

Dim maxid As Object
Dim strid As String
Dim intid As Integer
Dim cmdid As New MySqlCommand

cmdid.Connection = cnn_MYSQL
cmdid.CommandText = "SELECT MAX(printed_id) as maxid FROM imports"
maxid = cmdid.ExecuteScalar

If maxid Is DBNull.Value Then
    intid = "001"
Else
    strid = CType(maxid, String)
    intid = CType(strid, String)
    intid = intid + 1
End If

Dim autoid As String = frm_Main_Menu.lblCompany.Text & intid.ToString().PadLeft(3, "001")

Dim cmd66 As New MySqlCommand
cmd66.Connection = cnn_MYSQL
cmd66.CommandText = "UPDATE imports " & _
    " SET printed='" & "Y" & "', printed_id='" & autoid & "'" & _
    " WHERE TIN = '" & id_selected &"'"
cmd66.ExecuteNonQuery()

1 个答案:

答案 0 :(得分:1)

您要将这行String类型的整个ID段分配给此行的Integer字段/变量,这是完全错误的,并导致InvalidCastException

intid = CType(strid, String) ' throws conversion error

正确的方法是从数字部分(即索引为3的第4个元素)开始,使用Substring()截去前缀,然后用Convert.ToInt32()Integer.Parse()将余数转换为整数方法:

' using Convert.ToInt32
intid = Convert.ToInt32(strid.Substring(3, 3))

' alternative with Integer.Parse
intid = Integer.Parse(strid.Substring(3, 3))

旁注:

更好地使用参数化查询而不是字符串连接来构建查询,请参见以下示例:

cmd66.CommandText = "UPDATE imports SET printed = 'Y', printed_id = @autoid WHERE TIN = @id_selected"
cmd66.Parameters.Add("@autoid", MySqlDbType.VarChar).Value = autoid
cmd66.Parameters.Add("@id_selected", MySqlDbType.Int).Value = id_selected
cmd66.ExecuteNonQuery()