如何将数据添加到现有行Sql Server数据库中

时间:2018-07-25 16:06:55

标签: c# asp.net sql-server

在我的项目中,我有学生数据库和两个网络表单。在数据库中有6列(电子邮件,密码,名称,电话,ExamStatus,分数)。我通过webform1插入电子邮件和密码值,并通过另一个Web表单插入名称和密码。实际上,webform1重定向到webform2。

这是我的webform1文件后面的代码:

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;

public partial class signin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void signupbtn_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Punam\\Desktop\\Project\\App_Data\\OnlineLearning.mdf;Integrated Security=True"))
        {
            SqlCommand cmd = new SqlCommand("insert into Student (Email, Password) values(@email, @password)", con );
            cmd.Parameters.AddWithValue("@email", txtboxemail.Text);
            cmd.Parameters.AddWithValue("@password", txtboxpass.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            Session["signup"] = txtboxemail.Text.ToString();
            Response.Redirect("profile.aspx");
        }
    }
}

和webform2文件的代码隐藏:

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;

    public partial class profile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["signup"] == null)
            {
                Response.Redirect("signup.aspx");
            }
        }

        protected void btnsave_Click(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Punam\\Desktop\\Project\\App_Data\\OnlineLearning.mdf;Integrated Security=True"))
            {
                string mail = Session["signup"].ToString();
                SqlCommand cmd = new SqlCommand("Update Student set Name = @name, Phone = @phoneno where Email = + mail ", con);
                cmd.Parameters.AddWithValue("@name", txtboxname.Text);
                cmd.Parameters.AddWithValue("@phoneno", txtboxphone.Text);
                con.Open();
                cmd.ExecuteNonQuery();
                Response.Redirect("login.aspx");

            }
        }
    }

但是它抛出错误System.Data.SqlClient.SqlException:无效的列名'mail'。

1 个答案:

答案 0 :(得分:0)

1)请替换以下行以将会话中的SQL查询中的电子邮件地址传递给数据库

SqlCommand cmd = new SqlCommand("Update Student set Name = @name, Phone = @phoneno where Email = + mail ", con);

使用

SqlCommand cmd = new SqlCommand("Update Student set Name = @name, Phone = @phoneno where Email = @Email ", con);

2)添加@Email作为Command参数

cmd.Parameters.AddWithValue("@Email", mail);