I have created this code to add new records to the database however, every time I rum the code I get this error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
And I have no idea how to fix this error, I have looked online and tried different ways to fix it and none of them helped or fixed the problem.
The code is found below:
SqlCommand sdk = new SqlCommand("SELECT ([Id],[Title],[JobInfo],[DateSet],[DateDue],[WhoFor]) FROM Information_Schema.Columns FROM JobInformation", ConnectToDatabase);
ConnectToDatabase.Open();
SqlDataReader reader;
reader = sdk.ExecuteReader();
ConnectToDatabase.Close();
I believe it to be the first line of code, but I have no clue where the error could be within it.
I expect you mean something like:
ConnectToDatabase.Open();
using(var sdk = new SqlCommand(
"SELECT [Id],[Title],[JobInfo],[DateSet],[DateDue],[WhoFor] FROM JobInformation",
ConnectToDatabase))
using(var reader = sdk.ExecuteReader())
{
while(reader.Read()) { /* process row */
}
ConnectToDatabase.Close();
However, you may find it easier to use a tool like dapper :
var jobs = ConnectToDatabase.Query<JobInfo>(
"SELECT [Id],[Title],[JobInfo],[DateSet],[DateDue],[WhoFor] FROM JobInformation"
).AsList();
(which does everything including the open/close, and populates the columns into your own JobInfo
type that you need to create)
However, you say:
I have created this code to add new records to the database
in which case you'll need to use insert
, not select
- and the ExecuteNonQuery
method of SqlCommand
(or the Execute
method of "dapper").
For an insert:
using(var cmd = new SqlCommand(@"
insert JobInformation(Title, JobInfo, DateSet, DateDue, WhoFor)
values (@title, @jobInfo, @dateSet, @dateDue, @whoFor)", ConnectToDatabase))
{
cmd.Parameters.AddWithValue("@title", title);
cmd.Parameters.AddWithValue("@jobInfo", jobInfo);
cmd.Parameters.AddWithValue("@dateSet", dateSet);
cmd.Parameters.AddWithValue("@dateDue", dateDue);
cmd.Parameters.AddWithValue("@whoFor", whoFor);
cmd.ExecuteNonQuery();
}
or with dapper:
ConnectToDatabase.Execute(@"
insert JobInformation(Title, JobInfo, DateSet, DateDue, WhoFor)
values (@title, @jobInfo, @dateSet, @dateDue, @whoFor)",
new { title, jobInfo, dateSet, dateDue, whoFor});
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.