【发布时间】:2020-09-01 09:23:27
【问题描述】:
我在 Windows 窗体应用程序的 SQL 查询中收到错误消息。但我不明白查询中的错误在哪里。它甚至可以在 Visual Studio 查询脚本中工作。我在下面附上了重要文件。
在我的 Windows 窗体应用程序中,我收到一个 SQL 错误,这是屏幕截图。
错误是,
System.Data.SqlClient.SqlException: '',' 附近的语法不正确。'
这是尝试在校友表中创建行的函数。
public void createAlumni(int id, string fname, string lname, string sid, string age, string pyear, string present_address, string permanent_address, string father, string mother, string work, string email, string password, string subtitle, string desc) {
string sql = string.Format("INSERT INTO Alumni (Id, FirstName,LastName, StudentID, Email, Password, Age, PassingYear, PresentAddress, PermanentAddress, FathersName, MothersName, WorkPlace, ProfileSubtitle, ProfileDescription, ProfilePicture, Verified) VALUES ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', {6}, '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', {15}, {16});", id, fname, lname, sid, email, password, Convert.ToInt32(age), pyear, present_address, permanent_address, father, mother, work, subtitle, desc, null, 0);
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
int rowCount = cmd.ExecuteNonQuery();
if (rowCount == 0)
{
MessageBox.Show("Something went wrong");
}
else {
UpdateCount();
}
cmd.Connection.Close();
}
【问题讨论】:
-
始终在 SQL Server Management Studio 中测试您的查询,然后在 c# 中运行。 SSMS 中的错误消息比 c# 中的要好得多。命令文本中可能有错误。如果您的服务器有多个数据库,您必须添加到命令文本“使用数据库名称;”或将默认数据库添加到连接字符串中。