-6

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

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);
        }
    }
}

对我所缺少的任何帮助将不胜感激。

4

1 回答 1

2

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

打开连接后,您应该执行以下操作:

  • 构建命令
  • 添加命令所需的参数
  • 执行它
  • 关闭连接

像这样

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();

您不必在字段名称周围加上反标(SqlServer 不需要它们),参数名称也不应该用单引号括起来。

最后一点。如果user_id是一个身份字段,那么您不需要添加到命令文本中。

于 2013-04-15T11:45:45.733 回答