为什么我在`username`附近得到错误的语法?

时间:2014-07-27 05:21:37

标签: asp.net sql sql-server

public partial class adduser : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True");
    SqlCommand cmd = new SqlCommand("insert into login values username = @un,password = @ps, sequirity_que = @sq, ans = @answer,usertype = @ustp ");

    protected void Page_Load(object sender, EventArgs e)
    {    
    }

    protected void Button2_Click(object sender, EventArgs e)
    {    
        cmd.Connection = con;
        if (con.State != System.Data.ConnectionState.Open)
            con.Open();
        string un = txtusername.Text.Trim();
        string ps = txtpass.Text.Trim();
        string sq = txtseq.Text.Trim();
        string answer = txtans.Text.Trim();
        string ustp = DropDownList1.SelectedValue;
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("un", un);
        cmd.Parameters.AddWithValue("ps", ps);
        cmd.Parameters.AddWithValue("sq", sq);
        cmd.Parameters.AddWithValue("answer", answer);
        cmd.Parameters.AddWithValue("ustp", ustp);
        //string qry = "insert into login values (username = '" + txtusername.Text + "',password='" + txtpass.Text + "',sequirity_que='" + txtseq.Text + "',ans='" + txtans.Text + "',usertype='" + DropDownList1.SelectedValue + "') ";
        //SqlCommand md = new SqlCommand(qry,con);
        int n= cmd.ExecuteNonQuery();
        if(n>0)
        {
            Response.Write("User added");
        }
        else
        {
            Response.Write("fail");
        }
    }
}

1 个答案:

答案 0 :(得分:3)

这是INSERT INTO的正确语法:

SqlCommand cmd = new SqlCommand("insert into login (username, password, sequirity_que, ans, usertype) values (@un, @ps, @sq, @answer, @ustp)");

Some good examples