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
CodePudding user response:
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.