简体   繁体   English

SQL Server数据库存储数字数据为指数

[英]SQL Server Database store number data as exponential

I have a simple console application that reads from an excel file (source.xlsx) using OpenXML and do SQL Insert using ADO.NET to save the data to a SQL Server Database. 我有一个简单的控制台应用程序,该应用程序使用OpenXML从excel文件(source.xlsx)中读取,并使用ADO.NET进行SQL插入,以将数据保存到SQL Server数据库中。

I found problem when I read a decimal number like 0.00015, in which after saving to the SQL Server, it will be saved as "1.5 E-2" instead of 0.00015. 当我读取一个十进制数字(如0.00015)时发现了问题,在将其保存到SQL Server之后,它将被保存为“ 1.5 E-2”而不是0.00015。

This problem occurs when I try to run it in the production environment, but not occur when I try to run it in the staging environment (in the staging environment, it is saved as 0.00015). 当我尝试在生产环境中运行它时,会出现此问题,但是当我尝试在过渡环境中运行它时,不会发生此问题(在过渡环境中,它另存为0.00015)。

As far as the differences between the environment, I haven't found anything useful, so far all the settings looks the same (I most likely missing something important). 至于环境之间的差异,我还没有发现任何有用的东西,到目前为止,所有设置看起来都一样(我很可能错过了一些重要的东西)。

What is likely the root cause of the data stored that way and how to prevent it? 以这种方式存储数据的根本原因可能是什么?如何防止这种情况?

One likely cause would be if you are creating your SQL Insert statement using something like this: 一个可能的原因是如果您使用以下方式创建SQL Insert语句:

float value = 0.00015f;
string sql = "INSERT INTO [mytable] ([fieldname]) VALUES (" + value.ToString() + ")";

or 要么

string sql = string.Format("INSERT INTO [mytable] ([fieldname]) VALUES ({0})", value);

Both of these rely on .net's string formatting to produce valid SQL, which is not safe. 这两个都依靠.net的字符串格式来生成有效的SQL,这是不安全的。 The default string formatting will produce "The more compact of either fixed-point or scientific notation." 默认的字符串格式将产生“更紧凑的定点或科学计数法”。 So you will sometimes get scientific notation (1.5E-5), and sometimes fixed point formatting (0.00015). 因此,您有时会得到科学计数法(1.5E-5),有时会得到定点格式(0.00015)。 You may have different cultures on the server and development environments which could affect which format is more compact. 您在服务器和开发环境上的文化可能不同,这可能会影响哪种格式更紧凑。

The correct way to do this is to use parameters in your SQL, to avoid formatting problems and SQL injections: 正确的方法是在SQL中使用参数,以避免格式问题和SQL注入:

using (var cmd = dbConnection.CreateCommand()) {
    var prm = cmd.CreateParameter();
    prm.ParameterName = "value";
    prm.DbType = DbType.Single;
    prm.Direction = ParameterDirection.Input;
    prm.Value = 0.00015f;
    cmd.Parameters.Add(prm);

    cmd.CommandText = "INSERT INTO [mytable] ([fieldname]) VALUES (@value)";
    cmd.ExecuteNonQuery();
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM