C#中的double类型数据向SQL sqerver 存储与读取问题

1、存储

由于double类型在SQLsever中并没有对应数据,试过对应float、real类型,发现小数位都存在四舍五入的现象,目前我使用的是decimal类型,用此类型时个人觉得小数位数应该比自己的数据中小数位数设置的多一点,不然还是会出现四舍五入。

以下是我的代码,由于业务需求,我的数据库只存储一条数据,一直更新

 using (SqlConnection con = new SqlConnection(connectionString))
            {
                try
                {
                    //dbHelper = new DBHelper(BCSSqlConnection);
                    con.Open();
                    StringBuilder sbSql = new StringBuilder();

                    //sbSql.Append("insert into GpsData("
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C#的ADO.NET技术与SQL Server进行交互,具体的步骤如下: 1. 引入命名空间 ```csharp using System.Data.SqlClient; ``` 2. 建立数据库连接 ```csharp string connectionString = "Data Source=<server_name>;Initial Catalog=<database_name>;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); ``` 其,`<server_name>`为SQL Server的名称,`<database_name>`为要连接的数据库名称。 3. 打开数据库连接 ```csharp connection.Open(); ``` 4. 创建SQL语句并执行 ```csharp string sql = "INSERT INTO PointTab (x, y, z) VALUES (1.0, 2.0, 3.0);"; SqlCommand command = new SqlCommand(sql, connection); int rowsAffected = command.ExecuteNonQuery(); ``` 其,`PointTab`为要插入数据的表名,`(x, y, z)`为表的列名,`VALUES (1.0, 2.0, 3.0)`为要插入的数据。`ExecuteNonQuery`方法返回受影响的行数,可以用来判断插入是否成功。 5. 查询插入的数据并输出到控制台 ```csharp string selectSql = "SELECT * FROM PointTab;"; SqlCommand selectCommand = new SqlCommand(selectSql, connection); SqlDataReader reader = selectCommand.ExecuteReader(); while (reader.Read()) { double x = reader.GetDouble(0); double y = reader.GetDouble(1); double z = reader.GetDouble(2); Console.WriteLine($"x={x}, y={y}, z={z}"); } ``` 其,`SELECT * FROM PointTab`为要查询的SQL语句,`SqlDataReader`对象用于读取查询结果,`GetDouble`方法用于获取列的值。 6. 关闭数据库连接 ```csharp connection.Close(); ``` 完整的代码如下: ```csharp using System; using System.Data.SqlClient; namespace ConsoleApp { class Program { static void Main(string[] args) { string connectionString = "Data Source=<server_name>;Initial Catalog=<database_name>;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); string sql = "INSERT INTO PointTab (x, y, z) VALUES (1.0, 2.0, 3.0);"; SqlCommand command = new SqlCommand(sql, connection); int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine($"Rows affected: {rowsAffected}"); string selectSql = "SELECT * FROM PointTab;"; SqlCommand selectCommand = new SqlCommand(selectSql, connection); SqlDataReader reader = selectCommand.ExecuteReader(); while (reader.Read()) { double x = reader.GetDouble(0); double y = reader.GetDouble(1); double z = reader.GetDouble(2); Console.WriteLine($"x={x}, y={y}, z={z}"); } connection.Close(); } } } ``` 需要将`<server_name>`和`<database_name>`替换为实际的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值