[英]How to fix “Specified Cast Is Not Valid” error when retrieving data from table to confirm if record exists?
I'm using my program to add accounts to a database. 我正在使用我的程序将帐户添加到数据库。 I'm generating a random account number, checking if that account number exists in the database, and using it to create a new account if it doesn't.
我正在生成一个随机帐号,检查该帐号是否存在于数据库中,并使用它创建一个新帐号(如果不存在)。 However, I am getting the error "Specified Cast Is Not Valid" on the line
Int32? RecordExist = (Int32?)check_Records.ExecuteScalar();
但是,我在行
Int32? RecordExist = (Int32?)check_Records.ExecuteScalar();
上收到错误“指定的转换无效” Int32? RecordExist = (Int32?)check_Records.ExecuteScalar();
Int32? RecordExist = (Int32?)check_Records.ExecuteScalar();
. 。
I have tried .Convert.ToInt32
, just int
, double
and I have tried inspecting it as an object before the cast but I can't figure out what the problem is. 我已经尝试过
.Convert.ToInt32
,只是int
, double
并且我已经尝试在.Convert.ToInt32
之前将其作为对象进行检查,但是我不知道是什么问题。
string AccountNumber;
bool accountExists = true;
while (accountExists)
{
//GENERATE A RANDOM ACCOUNT NUMBER
Random rnd = new Random();
int acc1 = rnd.Next(0000, 9999);
int acc2 = rnd.Next(0000, 9999);
AccountNumber = "2000-" + acc1 + "-" + acc2 + ";";
using (MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.ConnectionString))
{
conn.Open();
//CHECK WHETHER ACCOUNT NUMBER EXISTS.
string Query = @"SELECT COUNT(*) FROM accounts WHERE Account_Number = '" + AccountNumber + "'";
using (MySqlCommand check_Records = new MySqlCommand(Query, conn))
{
Int32? RecordExist = (Int32?)check_Records.ExecuteScalar();
if (RecordExist.HasValue && RecordExist.Value > 0)
{
//ACCOUNT EXISTS, GENERATE ANOTHER ACCOUNT NUMBER
accountExists = true;
break;
}
else
{
//ACCOUNT DOES NOT EXIST, USE ACCOUNT NUMBER
accountExists = false;
lblNewAccountNumber.Text = AccountNumber;
}
}
conn.Close();
Thanks for your help in advance, and I apologise if I've made any mistakes! 感谢您的事先帮助,如果我有任何错误,我深表歉意!
EDIT: The type I was casting to was incorrect, and using the immediate window I was able to see that it needed to be Int64
. 编辑:我正在转换为该类型是不正确,并且使用立即窗口,我能够看到它需要为
Int64
。 It now works! 现在可以使用了! Thanks!
谢谢!
You should try to hold the ExecuteScalar
value to an object
type variable, then find out in debugging what is its type, and then apply the cast. 您应该尝试将
ExecuteScalar
值保留给object
类型变量,然后在调试中找出其类型,然后应用强制转换。 As is mentioned by @Alex K in the comments section. 正如@Alex K在评论部分中提到的。 Hope it works.
希望它能工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.