Hi please help I keep getting the error System.Data.SqlClient.SqlException: 'Incorrect syntax near '#'.' below is the code Thanks
private void AddBirthDayToCal(int startDayAtFlNumber)
{
var startDate = new DateTime(currentDate.Year, currentDate.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
SqlConnection FamilyMembersConnection;
FamilyMembersConnection = new SqlConnection("Data Source =.\\SQLEXPRESS; AttachDbFilename = " + Application.StartupPath + "\\MyFamily.mdf; Integrated Security = True; Connect Timeout = 30; User Instance = True");
FamilyMembersConnection.Open();
FamilyMembersCommand = new SqlCommand($"select * from FamilyMembers where Birthday between #{startDate.ToShortDateString()}# and #{endDate.ToShortDateString()}#", FamilyMembersConnection);
FamilyMembersAdapter = new SqlDataAdapter();
FamilyMembersAdapter.SelectCommand = FamilyMembersCommand;
FamilyMembersTable = new DataTable();
FamilyMembersAdapter.Fill(FamilyMembersTable);
foreach (DataRow row in FamilyMembersTable.Rows)
{
var BirthDay = DateTime.Parse(Conversions.ToString(row["BirthDay"]));
var link = new LinkLabel();
link.Tag = row["FamilyMembersID"];
link.Name = $"link{row["FamilyMembersID"]}";
link.Text = Conversions.ToString(row["First_Name"]);
listFlDay[BirthDay.Day - 1 + (startDayAtFlNumber - 1)].Controls.Add(link);
}
}
It's because you put '#' in the query
FamilyMembersCommand = new SqlCommand($"select * from FamilyMembers where Birthday between #{startDate.ToShortDateString()}# and #{endDate.ToShortDateString()}#", FamilyMembersConnection);
Change it to be like this
FamilyMembersCommand = new SqlCommand($"select * from FamilyMembers where Birthday between '{startDate.ToShortDateString()}' and '{endDate.ToShortDateString()}'", FamilyMembersConnection);
The # in sql allows you to reference a temporary object or procedure within the current session. That being said, you shouldn't need any # in the query. I'm assuming you'll want to replace those with single quotes as the string interpolation you are doing should resolve the properties you are passing in.
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.