简体   繁体   English

将varchar转换为数值数据类型的算术溢出错误。 尝试从数据库读取时并非每次都会发生

[英]Arithmetic overflow error converting varchar to data type numeric. when trying to read from a database DOES NOT happen every time

I'm trying to read in from a local database and create and return an object. 我正在尝试从本地数据库中读取数据,并创建并返回一个对象。 my code works fine the first 3 times through the loop that calls it and then fails giving me an error: Arithmetic overflow error converting varchar to data type numeric. 我的代码在调用它的循环的前3次中运行良好,然后失败,给了我一个错误:将varchar转换为数值类型的算术溢出错误。 I've done plenty of debugging and the error is being thrown at reader.Read(). 我已经进行了很多调试,并且错误被抛出给reader.Read()。 To my knowledge I'm not converting anything there, and all my research has turned up completely different sources for this error. 据我所知,我在那里没有进行任何转换,并且我的所有研究都为该错误找到了完全不同的来源。 any help would be greatly appreciated. 任何帮助将不胜感激。

System.Data.SqlClient.SqlDataReader reader;
/*Initialize Variables*/
        using (SqlCommand cmd = GetCommand("SELECT * FROM tblInventoryItem where InvoiceID = " + InvoiceNumber))
        {
            //Do Work...
            try
            {
                cmd.Connection.Open();
                reader = cmd.ExecuteReader();

                InventoryItem i;
                NItem ni;
                InventoryDataRepository2 idr = new InventoryDataRepository2();

                while (reader.Read())
                {
                    //Create an instance of the object....
                    i = new InventoryItem();
                    ni = new NItem();

                    ni.ItemNumber = (string)reader["ItemNumber"];
                    InventoryItem invitem = (InventoryItem)idr.GetItem(ni.ItemNumber);
                    ni.Title = invitem.Item.Title;
                    ni.Model = invitem.Item.Model;
                    ni.RetailPrice = invitem.Item.RetailPrice;
                    ni.WholesalePrice = invitem.Item.WholesalePrice;
                    i.Item = ni;
                    i.Quantity = Convert.ToInt32(reader["Quantity"]);


                    allItems.Add(i);
                }

EDIT: stacktrace: 编辑:stacktrace:

 at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
 at System.Data.SqlClient.SqlDataReader.TryHasMoreRows(Boolean& moreRows)
 at System.Data.SqlClient.SqlDataReader.TryReadInternal(Boolean setTimeout, Boolean& more)
 at System.Data.SqlClient.SqlDataReader.Read()
 at NeweggDistributor.InventoryItemDataRepository.GetAllItemsInInvoice(String InvoiceNumber) in c:\Users\AJ\Documents\Visual Studio 2012\Projects\NeweggDistributor\NeweggDistributor\InventoryItemDataRepository.cs:line 90
 Arithmetic overflow error converting varchar to data type numeric.

I agree with Eric J. i don't believe Reader.Read() would throw such an error. 我同意EricJ。我不认为Reader.Read()会引发此类错误。 What i see is likely to throw such an error tho is if the Quantity field in the DB is a string and cannot be converted to an integer, or if it is null in the DB because null cannot be converted to any integer. 我看到的很可能会引发此类错误,例如,如果DB中的“数量”字段是字符串并且无法转换为整数,或者在DB中为null,因为无法将null转换为任何整数。 other possibilities are the RetailPrice and WholesalePrice fields. 其他可能性是RetailPrice和WholesalePrice字段。 Perhaps you can comment out those lines and make sure you don't get the same error when they are commented out. 也许您可以注释掉这些行,并确保注释掉后不会出现相同的错误。 then you can uncomment each field one at a time, testing that each field one new field at a time. 那么您可以一次取消注释每个字段,一次测试每个字段一个新字段。

My first guess is that i.Quantity = Convert.ToInt32(reader["Quantity"]); 我的第一个猜测是i.Quantity = Convert.ToInt32(reader["Quantity"]); is trying to convert a varchar field into an int and the varchar string is not numeric. 正在尝试将varchar字段转换为int且varchar字符串不是数字。 I hardly ever use Convert.ToInt32 or C# casting for situations like this because they can throw unexpected nasty errors. 在这种情况下,我几乎不会使用Convert.ToInt32或C#强制转换,因为它们会引发意外的令人讨厌的错误。 I create a separate method that converts what i want, and i pass it a default value that is returned if the conversion cannot be performed. 我创建了一个单独的方法来转换我想要的内容,然后将无法传递的默认值传递给它。 Thus i use a 'defaultValue' parameter in my conversion methods. 因此,我在转换方法中使用了“ defaultValue”参数。

Your query is 您的查询是

SELECT * 
FROM tblInventoryItem 
WHERE InvoiceID = 1234

My guess is that InvoiceID in the database is a varchar field. 我的猜测是数据库中的InvoiceID是varchar字段。 This means that you are comparing an integer with a varchar in the where clause. 这意味着您要在where子句中比较整数和varchar。 Implicit conversions changes your query to 隐式转换会将查询更改为

SELECT * 
FROM tblInventoryItem 
WHERE CONVERT(int, InvoiceID) = 1234

You will get an error if any InvoiceID in the database contains something which will not fit into an integer. 如果数据库中的任何InvoiceID包含不适合整数的内容,您都会收到错误消息。

The arithmetic overflow error make the most probable cause an invoiceid > 2147483648 算术溢出错误最可能导致发票> 2147483648

Note that the error will not happen if your InvoiceNumber is also to big for an integer. 请注意,如果您的InvoiceNumber也大于整数,则不会发生该错误。

SELECT * 
FROM tblInventoryItem 
WHERE InvoiceID = 5000000000

will work because it is changed to 将起作用,因为它已更改为

SELECT * 
FROM tblInventoryItem 
WHERE CONVERT(bigint, InvoiceID) = 5000000000

The solution is of course to use parameters 解决方案当然是使用参数

command.CommandText = @"SELECT * " +
                      @"FROM tblInventoryItem " +
                      @"WHERE InvoiceID = @InvoiceNumber";
command.Parameters.Add("@InvoiceNumber", SqlDbType.VarChar).Value = InvoiceNumber;

(You can also use a parameter of type SqlDbtype.BigInt if you are sure InvoiceID only contain numbers) (如果您确定InvoiceID仅包含数字,则也可以使用SqlDbtype.BigInt类型的参数)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将varchar转换为数值数据类型的算术溢出错误。 asp.net中的错误 - Arithmetic overflow error converting varchar to data type numeric. Error in asp.net 将数据类型varchar转换为数字时出错。 2014年1月17日 - Error converting data type varchar to numeric. 1-17-2014 将数据类型varchar转换为数字时出错。 我使用了varchar数据类型,并尝试插入18-24值 - Error converting data type varchar to numeric. I used varchar data type and trying to insert 18-24 value “将数据类型 nvarchar 转换为数字时出错。” - “Error converting data type nvarchar to numeric.” 在var.net中将varchar转换为数值类型的算术溢出错误 - Arithmetic overflow error converting varchar to data type numeric in asp.net 在SQL Server 2008中将varchar转换为数值数据类型时发生算术溢出错误 - An arithmetic overflow error occurred while converting varchar to numeric data type in SQL Server 2008 c# 中的 ExecuteNonQuery() 抛出异常 - 将数字转换为数据类型数字的算术溢出错误 - ExecuteNonQuery() from c# throwing exception - arithmetic overflow error converting numeric to data type numeric 流利的NHibernate在插入/保存时导致“将数字转换为数据类型数字的算术溢出错误” - Fluent NHibernate cause an “Arithmetic overflow error converting numeric to data type numeric” on insert/save SQLException:将数据类型varchar转换为数值时出错 - SQLException: Error converting data type varchar to numeric 错误System.Data.SqlClient.SqlException:'将数据类型nvarchar转换为数字时出错。 在c#中 - Error System.Data.SqlClient.SqlException: 'Error converting data type nvarchar to numeric.' in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM