首页 > 解决方案 > 如何从正在运行的 asp.net 网站上的 SQL 表中更改列名?

问题描述

我用 ASP.NET 创建了一个连接到 SQL 数据库的网站。

该网站在网格视图的帮助下显示了一个表格。

我的目标是用户可以向该表添加一个列并为其命名。在文本框和按钮的帮助下。

到目前为止,我可以通过单击按钮为表格添加一列,但我不知道如何使用 TextBox 为列命名

private void disp_data()
{
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select * from table1";
    cmd.ExecuteNonQuery();
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(cmd);                                                
    da.Fill(dt);
    GridView3.DataSource = dt;
    GridView3.DataBind();
}

---尝试1

protected void AddRow_Click(object sender, EventArgs e)
{

    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;         
    cmd.CommandText = "ALTER TABLE table1 ADD '"+TextBox3.Text+"' VARCHAR(50) NULL;";            
    cmd.ExecuteNonQuery();

    disp_data();
}

---尝试2

protected void AddRow_Click(object sender, EventArgs e)
{

    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    string Columnname = Convert.ToString(TextBox3.Text);
    cmd.CommandText = "ALTER TABLE table1 ADD @CName VARCHAR(50)   NULL;";
    cmd.Parameters.AddWithValue(@"CName", Columnname);
    cmd.ExecuteNonQuery();

    disp_data();
}

protected void AddRow_Click(object sender, EventArgs e)
{
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;         
    cmd.CommandText = "ALTER TABLE table1 ADD NewColumn VARCHAR(50)        NULL;";            
    cmd.ExecuteNonQuery();

    disp_data();
}                           // This works

---尝试1

System.Data.SqlClient.SqlException:“'Textboxcontent' 附近的语法不正确。”

---尝试2

System.Data.SqlClient.SqlException:“'@CName' 附近的语法不正确。”

标签: c#asp.netsql-server

解决方案


我不建议尝试 1,因为它容易受到 SQL 注入的影响。尝试 2 不起作用,因为您使用逐字字符串而不是@CName用作字符串。

protected void AddRow_Click(object sender, EventArgs e) {

  SqlCommand cmd = con.CreateCommand();
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "ALTER TABLE table1 ADD @CName VARCHAR(50)   NULL;";
  cmd.Parameters.AddWithValue("@CName", TextBox3.Text);
  cmd.ExecuteNonQuery();
}

推荐阅读