在SQL语句中动态设置表名和列名

时间:2015-08-04 07:48:12

标签: c# sql-server

我是C#的新手。我必须从Windows窗体获取输入并执行sql语句。在这里,我必须从用户输入中获取表名和列名。 我写了这样的代码。

string ment = String.Format("update {0} set {1} ='" + radioButton1.Text + "' where RoomId='" + textBox8.Text + "'", textBox7.Text, comboBox1.SelectedItem); 
cmd = new SqlCommand(ment, con);
cmd.ExecuteNonQuery();

这给出了一个例外。

  

它说“''''附近的语法不正确。

对我错过的任何想法?

2 个答案:

答案 0 :(得分:1)

您的表名或列名可能包含不正确的字符。用MySQL中的字符`或MSSQL中的括号包装它们。

MSSQL版本。

string ment = String.Format("update [{0}] set [{1}] ='" + radioButton1.Text + "' where RoomId='" + textBox8.Text + "'", textBox7.Text, comboBox1.SelectedItem); 
cmd = new SqlCommand(ment, con);
cmd.ExecuteNonQuery();

MySQL版本。

string ment = String.Format("update `{0}` set `{1}` ='" + radioButton1.Text + "' where RoomId='" + textBox8.Text + "'", textBox7.Text, comboBox1.SelectedItem); 
cmd = new SqlCommand(ment, con);
cmd.ExecuteNonQuery();

答案 1 :(得分:0)

我知道这个帖子已经老了,但@han上面的正确答案是sql注入...

您可以使用QuoteIndetifier,这是一个示例

 StringBuilder SQLtext = new StringBuilder();
            SqlCommandBuilder sqlBuilder = new SqlCommandBuilder();
            string MyColumn = sqlBuilder.QuoteIdentifier(Radio_range.SelectedValue);
            SQLtext.AppendLine(" With ctemp as( ");
            SQLtext.AppendLine(" select convert(varchar(10),sysDate,102) sysDate,convert(varchar(10),WeekDate,102) WeekDate,[Month],[Quarter],[Year] ");
            SQLtext.AppendLine(" from sysCalendar ");
            SQLtext.AppendLine(" where sysdate<=(select max(nominal_date) from ATTENDANCE_AGENT_T) ");
            SQLtext.AppendLine(" and sysDate>=dateadd(MONTH,-12,getdate()) ");
            SQLtext.AppendLine(" ) ");
            SQLtext.AppendFormat(" select distinct {0} as mydate from ctemp order by {1}  desc ", MyColumn, MyColumn);
            string constr = ConfigurationManager.ConnectionStrings["CIGNAConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(SQLtext.ToString()))
                {
                    cmd.CommandType = CommandType.Text;
                    //cmd.Parameters.AddWithValue("@mydate", Radio_range.SelectedValue);
                    cmd.Connection = con;
                    con.Open();
                    DropDownList_Date.DataSource = cmd.ExecuteReader();
                    DropDownList_Date.DataTextField = "mydate";
                    DropDownList_Date.DataValueField = "mydate";
                    DropDownList_Date.DataBind();
                    con.Close();
                }
            }