无法插入数据库asp.net C#

时间:2013-12-11 21:10:31

标签: c# mysql asp.net .net

我的代码出了问题。插入代码不起作用。谁能告诉我我做错了什么?当用户单击按钮时,代码应该将用户名,密码和角色插入到我的数据库中,但是我的数据库中没有任何内容。

namespace Login_role
{
    public partial class Register : System.Web.UI.Page
    { 

        string strConnString = ConfigurationManager.ConnectionStrings["victs"].ConnectionString;
        SqlCommand com;

        protected void btn_register_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(strConnString);
            com = new SqlCommand();
            com.Connection = con;
            com.CommandType = CommandType.Text;
            com.CommandText = "Insert into Login values(@UserName,@Password,@Role)";
            com.Parameters.Clear();
            com.Parameters.AddWithValue("@UserName", txt_UserName.Text);
            com.Parameters.AddWithValue("@Password", txt_Password.Text);
            com.Parameters.AddWithValue("@Role", rbtRole.SelectedValue);
            if (con.State == ConnectionState.Closed)
                con.Open();
            com.ExecuteNonQuery();
            con.Close();
            lblmsg.Text = "Successfully Registered!!!";
            clear();
        }
        private void clear()
        {
            txt_UserName.Text = "";
            rbtRole.ClearSelection();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

除非这些是您的LOGIN表中唯一的3列,否则SQL Server(我的假设)将不会执行您的命令文本:

com.CommandText = "Insert into Login values(@UserName,@Password,@Role)";

但是这应该抛出异常(即使其余列上有默认值):

"Column name or number of supplied values does not match table definition."

尝试在命令文本中列出列名称:

string sqlCmd = "Insert into Login (UserName, Password, Role) " +
                "values(@UserName,@Password,@Role)";
com.CommandText = sqlCmd;
com.CommandType = CommandType.Text; // <-- SQL doesn't have to guess!

看看这是否有所作为。