mysql - 生成字母数字 ID 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()
解决方案
您正在将具有String
类型的整个 ID 段分配给Integer
该行上的字段/变量,这是完全错误的并导致InvalidCastException
:
intid = CType(strid, String) ' throws conversion error
Substring()
正确的方法是使用从数字部分(即索引为 3 的第 4 个元素)开始切掉前缀,然后使用Convert.ToInt32()
orInteger.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()
推荐阅读
- r - 如何在与 R Shiny 应用程序相同的窗口中打开 PDF 文件?
- javascript - Facebook 分享对话框/提要对话框和自定义标题/描述
- python - SQLalchemy 核心连接和选择没有重复的字段
- android - ItemDecoration 在 NestedScrollView 中不起作用
- sql - 创建新表时出现 SQL 错误,我缺少什么
- angular - Angular从另一个元素获取输入字段值
- swift - 用CGEvent模拟CTRL+Space切换键盘输入出现显示键盘切换菜单
- python - 使用ubuntu的Python设置工具安装错误
- rx-java2 - rxjava2-jdbc:对 toIterable() 的迭代是阻塞的,线程 reactor-http-nio-2 不支持此功能
- vue.js - 在创建它的同一模块中使用 getter