c# - 如何从正在运行的 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' 附近的语法不正确。”
解决方案
我不建议尝试 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();
}
推荐阅读
- python - 如何沿轴约束极坐标热图?
- github - github 默认分支是 main 但不是 master
- go - 无效参数:未找到装甲数据
- meshlab - 如何在 MESHLab 中保存已编辑的网格?
- node.js - PostgreSQL last inserted ID not auto-increment typescript sequelize
- pdf - 来自电子表格的 PDF 格式的 Google App 脚本电子邮件
- excel - 下拉列表选择已更改 - 单元格变灰
- android - 如何在 Android 的微调器(下拉)中添加单独的文本颜色和背景颜色?
- php - 缓存问题 - 刷新页面(F5 按钮)以查看修改的内容
- datatable - 如何从数据表中的最新日期和时间排序