I'm creating a window form that displays a Calendar Event.
And when I add an event on specific date, I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'value'
at the line cmd.ExecuteNonQuery();
.
This is my code:
namespace PRN_Project
{
public partial class EventForm : Form
{
String ConnectionString = "server=DESKTOP-7NUQVBN; database=Calendar; uid=sa; pwd=123";
public EventForm()
{
InitializeComponent();
}
private void EventForm_Load(object sender, EventArgs e)
{
tbDate.Text = UserControlDays.static_day "/" CalendarForm.static_month "/" CalendarForm.static_year;
}
private void btSave_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
String sql = "INSERT INTO CalendarEvent (TimeDate, EventName) VALUE (?, ?)";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("TimeDate", tbDate.Text);
cmd.Parameters.AddWithValue("EventName", tbEvent.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Saved!");
cmd.Dispose();
conn.Close();
}
}
}
I am using SQL Server authentication.
The datatype for TimeDate
and EventName
is varchar(255)
.
CodePudding user response:
try this one:
private void btSave_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConnectionString);
String sql = "INSERT INTO CalendarEvent(TimeDate, EventName)values(@TimeDate,@EventName)";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@TimeDate", tbDate.Text);
cmd.Parameters.AddWithValue("@EventName", tbEvent.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Saved !!!");
cmd.Dispose();
conn.Close();
}
and you can use TRY Catch Finally
private void btSave_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConnectionString);
String sql = "INSERT INTO CalendarEvent(TimeDate, EventName)values(@TimeDate,@EventName)";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("@TimeDate", tbDate.Text);
cmd.Parameters.AddWithValue("@EventName", tbEvent.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Saved !!!");
}
catch
{
}
finally
{
conn.Close();
}
}