单击事件不添加数据

本文关键字:数据 添加 事件 单击 | 更新日期: 2023-09-27 18:09:29

所以我有以下代码,但数据库没有更新,页面似乎没有显示任何错误。在构建中没有错误,但仍然没有数据输入。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class ValidateMe : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection("Data Source=MICROSOF-58B8A5'SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
        connection.Open();
        if (TextBox8.Text == TextBox9.Text)
        {
            string UserName = TextBox7.Text;
            string Password = TextBox8.Text;
            string FirstName = TextBox1.Text;
            string LastName = TextBox2.Text;
            string Address = TextBox3.Text;
            string PostCode = TextBox4.Text;
            string Phone = TextBox5.Text;
            string Email = TextBox6.Text;
            string sqlquery = "INSERT INTO `users` (`user_id`, `username`, `first_name`, `last_name`, `password`, `address`, `postcode`, `phone`, `email`, `level`) VALUES (NULL, '@UserName', '@FirstName', '@LastName', '@Password', '@Address', '@PostCode', '@Phone', '@Email');";
            SqlCommand command = new SqlCommand(sqlquery, connection);
        }
    }
}

如果有任何帮助,我将不胜感激。

单击事件不添加数据

您的代码遗漏了几个(基本)步骤。

打开连接后,你应该做:

    构建命令
  • 添加命令
  • 所需的参数
  • 关闭连接
这样的

string sqlquery = "INSERT INTO users (username, first_name, last_name, password," + 
                  "address, postcode, phone, email, level) VALUES " + 
                  "(@UserName, @FirstName, @LastName, @Password, " + 
                  "@Address, @PostCode, @Phone, @Email);";
SqlCommand command = new SqlCommand(sqlquery, connection);
command.Parameters.AddWithValue("@username", Username);
.....
// Add the other parameters
.....
// Execute the query
command.ExecuteNonQuery();
// Close the connection
connection.Close();

你不需要在你的字段名周围放上backsticks (SqlServer不需要它们),参数名也不应该用单引号括起来。

最后一点。如果user_id是标识字段,则不需要添加到命令文本中。