【问题标题】:Getting error due to column name of my database table is "from"由于我的数据库表的列名是“来自”而出现错误
【发布时间】:2014-10-10 21:08:46
【问题描述】:

我的数据库列名是“from”,但是当我将列名更改为其他名称时出现错误,没有发生错误。为什么?

    protected void Button1_Click(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    con.Open();
    string qry="insert into Mynew(name,age,from,address,job)values(@name,@age,@from,@address,@job)";
    SqlCommand cmd= new SqlCommand(qry, con);
    cmd.Parameters.AddWithValue("@name", TextBox1.Text);
    cmd.Parameters.AddWithValue("@age", TextBox2.Text);
    cmd.Parameters.AddWithValue("@from",TextBox3.Text);
    cmd.Parameters.AddWithValue("@address", TextBox4.Text);
    cmd.Parameters.AddWithValue("@job", TextBox5.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    }

当我将列名更改为城市时没有出现错误,为什么会发生?

【问题讨论】:

  • From 是保留的,不能作为列名
  • 如何更改列名?
  • 通过编辑数据库表列名。
  • check this link 如果您使用的是 SQL Server。

标签: c# asp.net database ado.net


【解决方案1】:

from 是 SQL 中的保留关键字。如果您想将其用作表名,则必须通过以下方式对其进行转义:

  • 把它放在反引号之间(MySQL 和其他)
  • 将其放在方括号之间(MS Access、SQL 服务器)

所以

insert into Mynew(name,age,`from`,address,job)values(@name,@age,@from,@address,@job)

insert into Mynew(name,age,[from],address,job)values(@name,@age,@from,@address,@job)

取决于您使用的数据库。

为避免混淆,显然最好使用不同的列名。

【讨论】:

  • 您使用的是什么数据库? SQL Server?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 2021-08-19
  • 2020-03-03
  • 1970-01-01
相关资源
最近更新 更多