繁体   English   中英

由于我的数据库表的列名出现错误,是“ from”

[英]Getting error due to column name of my database table is “from”

我的数据库列名称是“ 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();
    }

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

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

  • 将其放在反引号之间(MySQL和其他)
  • 将其放在方括号之间(MS Access,SQL Server)

所以要么

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)

取决于您使用的数据库。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM