从类型“DBNull”到“Integer”类型的转换无效。 [英] Conversion from type 'DBNull' to type 'Integer' is not valid.

查看:393
本文介绍了从类型“DBNull”到“Integer”类型的转换无效。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dim cmd As New SqlCommand
       cmd.CommandType = CommandType.Text
       cmd.Connection = myconn
       cmd.CommandText = "select Max(token_no)+1 from billentry"
       myconn.Open()
       Dim a As Integer = cmd.ExecuteScalar
       myconn.Close()
       TextBox1.Text = a



它给出错误

从类型'DBNull'转换为'Integer'类型无效。

i想要在插入ist值时添加token_no为1


it gives error
Conversion from type 'DBNull' to type 'Integer' is not valid.
i want to add token_no is 1 when ist value was inserted

推荐答案

所以 - 没有行。

试试这个:

So - no rows.
Try this:
SELECT ISNULL(MAX(token_no) + 1, 0) from billentry



但......如果您使用它来生成唯一的数字,请不要这样做! SQL是一个多用户环境,使用这样的代码要求模糊,难以发现错误和混淆数据。改为使用IDENTITY规范字段,让SQL为你整理id。


But... if you are using this to generate unique numbers, don't do it! SQL is a multiuser environment, and using code like this is asking for obscure, difficult to spot bugs and confused data. Use an IDENTITY specification field instead, and let SQL sort out the id for you.


你的查询返回空值。

和从null转换为整数生成错误...

Your query returns null value.
and conversion from null to integers generate that error...
cmd.CommandText = "select Max(token_no)+1 from billentry"  'query returns null.
      
Dim a As Integer = cmd.ExecuteScalar 'Here you tried to convert row value which does not exist.





上面尝试的方法不方便。

如果你的查询大部分时间都返回空白并保持代码简单,因为它现在。

只需在转换之前添加一个IF。





如果你想要什么都不返回时允许空白。

然后,直接重定向查询输出。



The method you tried above is not convenient.
if your query returns blank most of times and keep the code simple as it is now.
Just add a IF before you convert it.

OR
If you want to allow blank in text when nothing returns.
then, directly redirect the Query Output.

TextBox1.Text = cmd.ExecuteScalar.toString()







如果单个值返回,您可以使用OleDBDataReader和ExecuteReader



OR
if single value returns you can use OleDBDataReader and ExecuteReader


这篇关于从类型“DBNull”到“Integer”类型的转换无效。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆