我正在尝试创建一个允许变量赋值的函数,但我一直收到错误:
private static void DatabaseSelect(string ToBeSelected, string WhichTable, string Equality1, string Equality12)
{
SqlConnection con = new SqlConnection(@"Connection");
var dataSet = new DataSet();
var cmd = new SqlCommand("SELECT Firstname FROM Student WHERE User_ID = '" + "001" + "'", con);
//var cmd = new SqlCommand("SELECT '"+ToBeSelected+"' FROM '"+WhichTable+ "' WHERE '"+Equality1+"' = '"+Equality12+"'", con);
var dataAdapter = new SqlDataAdapter { SelectCommand = cmd };
dataAdapter.Fill(dataSet);
Console.WriteLine( dataSet.Tables[0].Rows[0][ToBeSelected].ToString());
}
当我使用
行时var cmd = new SqlCommand("SELECT Firstname FROM Student WHERE User_ID = '" + "001" + "'", con);
理论上,当变量与上面的行相同时,与行相同
var cmd = new SqlCommand("SELECT '"+ToBeSelected+"' FROM '"+WhichTable+ "' WHERE '"+Equality1+"' = '"+Equality12+"'", con);
但是当我尝试运行下面的行时,它会显示错误消息(在Filling dataAdapter行中):
"未处理的类型' System.Data.SqlClient.SqlException'发生在System.Data.dll中 附加信息:' Student'附近的语法不正确。"
如果我不清楚,请说出来。非常感谢,谢谢。
答案 0 :(得分:1)
我确实看到了MySQL语法的一些问题
SELECT '"+ToBeSelected+"' FROM '"+WhichTable+ "' WHERE '"+Equality1+"' = '"+Equality12+"'"
应转换为:MySQL语句:
SELECT 'ColumnName' FROM 'TableName' WHERE 'ColumnName2' = 'SomeValue'"
我看到的第一个问题是所有的单引号。列名,表名应该用" ticks" (1左边的按钮)不是单引号。
我会从那里开始,我现在正在进一步阅读你的代码。