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).
INSERT INTO TABLE_NAME VALUES (COLUMN_1, COLUMN2)VALUESnotVALUE. And you should ideally use named parametersINSERT INTO CalendarEvent(TimeDate, EventName) values (@TimeDate, EventName). Also note:AddWithValueis Evil, specify parameter types and lengths explicitly. And you needusingblocks on the connection and command objects