我已经创建了一个监控公司项目进度的程序,但在我测试时遇到了一个非常古怪的问题。当我在电脑中的 windows 10 下进行测试时,创建了所有运行的按预期方式。但是当我在运行 Windows 7 和 8 的同事的计算机上测试时,我在sql查询代码中得到以下错误 "您的SQL语法中有错误,请查看与您的MySQL服务器版本对应的手册,以便在#01; 01附近使用正确的语法,其中teammember.Name =" SomeName"和项目=" SomeProject"'在第1行" 。导致错误的代码如下。
public void UpdateHoursWorked(string teamMember, string projectName, float hoursWorked)
{
SetSafeUpdates(false);
// Error HERE
using (MySqlCommand cmd = new MySqlCommand("update memberprojects " +
"join teammembers on Member = teammembers.TeamMembersID " +
"join projects on Project = projects.ProjectsID " +
"set HoursWorkedOnProject = HoursWorkedOnProject + " + hoursWorked + " " +
"where teammembers.Name = \"" + teamMember + "\" and projects.ProjectName = \"" + projectName + "\"", conn))
cmd.ExecuteNonQuery();
// Update the total hours worked in the projects table, and re-read the projects
UpdateTotalHoursWorked(projectName, hoursWorked);
OnUpdate(EventArgs.Empty);
}
我似乎无法确定问题,因为在Windows 10下程序运行良好,语法对我来说是正确的。关于什么可能导致问题的任何想法?
答案 0 :(得分:2)
使用Command.Parameters
编写查询。还可以使用@
在多行上连接字符串。 格式您的查询!
好处:
1)不会发生这样的问题
2)您受到sql注入保护
3)代码读/写更容易
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = @"
UPDATE
MemberProjects
JOIN
TeamMembers ON Member = TeamMembers.TeamMembersID
JOIN
Projects ON Project = Projects.ProjectsID
SET
HoursWorkedOnProject = HoursWorkedOnProject + @HoursWorked
WHERE
TeamMembers.Name = @Name AND
Projects.ProjectName = @ProjectName";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("@HoursWorked", hoursWorked);
cmd.Parameters.AddWithValue("@Name", teamMember);
cmd.Parameters.AddWithValue("@ProjectName", projectName);
cmd.ExecuteNonQuery();
}
我认为您可以轻松看到良好格式化和使用参数之间的区别。我建议你在会员面前写下表名,项目会更容易理解这个领域的位置。
答案 1 :(得分:0)
尝试使用单引号
的适当替换来避免双引号序列(和转义) "update memberprojects " +
"join teammembers on Member = teammembers.TeamMembersID " +
"join projects on Project = projects.ProjectsID " +
"set HoursWorkedOnProject = HoursWorkedOnProject + " + hoursWorked + " " +
"where teammembers.Name = '" + teamMember + "' and projects.ProjectName = '" + projectName + "'", conn))
cmd.ExecuteNonQuery();