简体   繁体   中英

Can't add a row to database after the query is fine

I am trying to add a row into the database but something seems wrong. The connection is okay and the query is fine too but after pressing the button the row isn't added.

       con.Open();
        SqlCommand cm = new SqlCommand("INSERT INTO Sports (Спорт) VALUES (@Спорт)",con);
        cm.Parameters.AddWithValue("@Спорт", tbAddSport.Text);
        try
        {
            int exec = cm.ExecuteNonQuery();
            if (exec > 0)
            {
                MessageBox.Show("Added");
            }
            else
            {
                MessageBox.Show("Error");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error (ex)");
            con.Close();
        }
        finally
        {
            con.Close();
            clearBoxes();
        }

If there is no exception. I see some possible problems.

You don't need to Close connection in catch block. If exception happen the con.Close() in finally will be execute always.

The other problems I can't find any documentation about cyrillic parameter names. It is possible to be not supported.

Try it like this:

SqlCommand cm = new SqlCommand("INSERT INTO Sports (Спорт) VALUES (@Sport)",con);
cm.Parameters.AddWithValue("@Sport", tbAddSport.Text);

It is bad practise to write cyrillic column names in database. Change name to Sport in the Sports Table.

Also are you sure that clearBoxes(); doesn't remove the possible exception.

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