首页 > 解决方案 > 在 C# 中向 SQL Server 添加十进制数

问题描述

我正在开发一个订购程序。订购时无法将产品价格添加到数据库中。价格是十进制的,如 24.99。

我的代码;

int table = Convert.ToInt32(lblTableNo.Text), product = Convert.ToInt32(formLogin.readData("select productID from tbProducts where productName='" + lblProduct.Text + "'")), piece = Convert.ToInt32(lblPiece.Text);
            float price = piece * float.Parse(formLogin.readData("select productPrice from tbProducts where productID=" + product));
            string time = System.DateTime.Now.ToShortTimeString();
            formLogin.runSql("insert into tbOrders (orderTable, orderUser, orderTime, orderProduct, orderPiece, orderPrice) values (" + table+ "," + formLogin.signer+ ",'" + time + "'," + product + "," + piece + "," + price + ")");

价格变量的值是“25.5”,而函数是“25,5”。这就是sql查询失败的原因。

我试图将价格变量转换为十进制。但结果并没有改变。

运行Sql代码;

    public static bool runSql(string sql)
    {
        SqlConnection cnn= connect();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cnn;
        cmd.CommandText = sql;
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
        cnn.Close();
        cmd.Dispose();
        return true;
    }

读取数据代码;

    public static string readData(string sql)
    {
        SqlConnection cnn= connect();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cnn;
        cmd.CommandText = sql;
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        return dr[0].ToString();
        dr.Close();
        cnn.Close();
    }

标签: c#sqlsql-serverdecimal

解决方案


推荐阅读