简体   繁体   中英

Exception occurs in ExecuteNonQuery function

I am trying to get some data in my MS SQL Database, but unfortunately, the ExecuteNonQuery function causes an "Error" or more accurately an Exception and stops the program. To get a quick overview, the project I am currently sitting on is a simple calendar that you should be able to save appointments in. I am doing this project to get a little bit better known with C# because I haven't worked a lot with it so please excuse me if I am doing simple mistakes.

Here is my code for the EventForm class where the Exception accurs:

using System.Data.SqlClient;

namespace Kalender
{
    public partial class EventForm : Form
    {
        public EventForm()
        {
            InitializeComponent();
        }

        public string conString = "Data Source=WS-UN-010122;Initial Catalog=calender;Integrated Security=True";

        private void EventForm_Load(object sender, EventArgs e)
        {
            txtdat.Text = UserControlDays.static_tag + "." + Form1.static_monat + "." + Form1.static_jahr;
        }

        private void btnsave_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(conString);
            con.Open();
            string sql = "INSERT INTO tbl_calender(Ereignis,Datum)values(?,?)";
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = sql;
            cmd.Parameters.AddWithValue("Ereignis", txtevent.Text);
            cmd.Parameters.AddWithValue("Datum", txtdat.Text);
            cmd.ExecuteNonQuery(); // <--------- Exception
            MessageBox.Show("gespeichert");
            cmd.Dispose();
            con.Close();
        }
    }
}

在此处输入图像描述

Here is the Message i get. If you ask which language it is written into, its german

SQL Server uses named parameters (not positional) by default; try instead:

const string sql = "INSERT INTO tbl_calender(Ereignis,Datum) values(@Ereignis,@Datum)";

You may also prefer to look at tools like Dapper, which will save a lot of pain here...

using var con = new SqlConnection(conString);
con.Execute(sql, new { Ereignis = txtevent.Text, Datum = txtdat.Text });

As a final thought: consider parsing the date into a DateTime before sending it to the database; the database should not be responsible for decisions around string formatting.

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