sql插入asp.net [英] sql insert into asp.net

查看:86
本文介绍了sql插入asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

con.Open();
SqlCommand cmd=new SqlCommand("INSERT INTO user(Firstname,Lastname,Email,Pass,Type)
    values(@first,@last,@email,@pass,@type)",con);
cmd.Parameters.Add("@first",SqlDbType.NVarChar).Value = txtfirst.Text;
cmd.Parameters.Add("@last",SqlDbType.NVarChar).Value = txtlast.Text;
cmd.Parameters.Add("@email",SqlDbType.NVarChar).Value = txtemail.Text;
cmd.Parameters.Add("@pass",SqlDbType.NVarChar).Value = txtpass.Text;
cmd.Parameters.Add("@type",SqlDbType.NVarChar).Value = "customer";
cmd.ExecuteNonQuery();
con.Close();

我的语法有什么问题,它说关键字'user'附近的语法不正确."

what is the problem with my syntax it says "Incorrect syntax near the keyword 'user'."

推荐答案

您应该使用分隔的标识符对表名 user 进行转义,

you should escape the table name user with delimited identifiers,

SqlCommand cmd=new SqlCommand("INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values(@first,@last,@email,@pass,@type)",con);

  • SQL Server保留关键字
  • SQL Server分隔标识符
  • 更新1

    通过以下方式折射代码

    • 使用 using 语句正确处理对象
    • 使用 Try-Catch 块正确处理异常
    • using using statement to properly dispose objects
    • using Try-Catch block to properly handle exceptions

    代码段:

    string _connStr = "connectionString here";
    string _query = "INSERT INTO [user] (Firstname,Lastname,Email,Pass,Type) values (@first,@last,@email,@pass,@type)";
    using (SqlConnection conn = new SqlConnection(_connStr))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            comm.CommandType = CommandType.Text;
            comm.CommandText = _query;
            comm.Parameters.AddWithValue("@first", txtfirst.Text);
            comm.Parameters.AddWithValue("@last", txtlast.Text);
            comm.Parameters.AddWithValue("@email", txtemail.Text);
            comm.Parameters.AddWithValue("@pass", txtpass.Text);
            comm.Parameters.AddWithValue("@type", "customer");
            try
            {
                conn.Open();
                comm.ExecuteNonQuery();
            }
            catch(SqlException ex)
            {
                // other codes here
                // do something with the exception
                // don't swallow it.
            }
        }
    }
    

    • AddWithValue
    • 添加(推荐一个)
    • 这篇关于sql插入asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆