简体   繁体   中英

save a decimal value in database c#

I am trying to save a value from text box into sql database. I am having the error as shown on the picture. my code below:

    public void datastore()
        {
            string Blerje, Shitje, Data;
            Blerje = usdollar_buy.Text;
            Shitje = usdollar_sell.Text;
            Data = dateTimePicker.Text;

            try
            {
                string constring = "Data Source=DELL;Initial Catalog=login_register;Integrated Security=True";

                /* Declaring Connection Variable */
                SqlConnection con = new SqlConnection(constring);
                String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] values ('" + Blerje + "','" + Shitje + "','" + Data + "')";

                /* Checking Connection is Opend or not If its not open the Opens */
                if (con.State != ConnectionState.Open)
                    con.Open();

                SqlCommand cmd = new SqlCommand(sql, con);

                /* Executing Stored Procedure */
                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Te dhenat u ruajten ne databaze");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

在此处输入图片说明

1. You might be having more columns in your table than mentioned values(3) in your query. so it is always good to specify the column names in your query for which columns you are inserting the values.

Try This:

INSERT INTO [TableName](COL1,COl2,COL3)
Values(Value1,Value2,Value3);

2. As you mentioned your columsn are decimals, you are inserting them as as strings by enclosing the values within single quotes.

You should not enclose the decima values within single quotes.

Suggestion : Your query is open to SQL Injection Attacks. I Would suggest you to use the Parameterised queries to avoid them.

change the datatype to (18,6) or so, whichever is suitable for you,

The second part of decimal data type shows how many digits do you require after the 'point'. In your case it's '0', so db is rounding it to nearest integer.

Source: http://msdn.microsoft.com/en-us/library/ms187746.aspx

You are missing the fields in your insert statement.

The database will try to determine the right columns and their order, but if you don't deliver all fields in the appropriate order, your query will fail.

So in short:

  1. Deliver all fields in the correct order ;
  2. Or: add the fields you want to fill in the insert .

Sample:

String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] (Blerje, Shitje, Data) values ('" + Blerje + "','" + Shitje + "','" + Data + "')";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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