生成字母数字id vb.net时出错

anhgbhbe  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(275)

我试图通过连接用户company+自动生成的id来生成一个唯一的id
我的字母数字输出为“snc001”,但当我试图生成下一个id时,出现以下错误:
从字符串“snc001”到类型“integer”的转换无效。
注:“snc”来自这个frm\u main\u 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()
5jvtdoz2

5jvtdoz21#

您正在分配整个id段 String 键入到 Integer 字段/变量,这是完全错误的 InvalidCastException :

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

正确的方法是使用 Substring() 从数字部分(即索引为3的第4个元素)开始,用以下任一方法将余数转换为整数 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()

相关问题