我想在ASP.NET列名中使用变量名作为列名。
我收到以下错误:
'二月'附近的语法不正确。
代码是
SqlConnection MyConn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\apptitude\projects\database\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
MyConn.Open();
int i,n=5;
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
Label1.Text = day.ToString();
if (day==1)
{
//for(i=1;i<=n;i++)
//{
//Label1.Text = "hi";
int j = 1;
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set **'"+month[mon]+"'=20";**
i = cmd.ExecuteNonQuery();
Label1.Text = i.ToString();
}
答案 0 :(得分:5)
您不需要将列名括在单引号(')中;因此:
update Yearly_data set 'February'=20
应该写成
update Yearly_data set February=20
如果您将代码更改为以下代码,则可以使用:
cmd.CommandText = "update Yearly_data set "+month[mon]+"=20";
但是,请注意,构建动态SQL语句应该谨慎行事,以免在SQL Injection attack上冒风险。
答案 1 :(得分:3)
如果一年中的每个月都是Yearly_data
中的ColumnName,那么请将您的代码行更改为:
cmd.CommandText = "update Yearly_data set ["+month[mon]+"]=20";
答案 2 :(得分:1)
除了已经给出的答案之外,框架还提供了使用DateTimeFormatInfo.GetMonthName函数获取月份名称的方法。
static string GetMonthName(DateTime sourceDate)
{
var dateFormatInfo = new DateTimeFormatInfo();
return dateFormatInfo.GetMonthName(sourceDate.Month);
}
cmd.CommandText = String.Format("update Yearly_data set {0} = 20", GetMonthName(DateTime.Now));