c# - 无法写入数据库

标签 c# asp.net sql

我有一个包含用户名、密码和用户标识符的网络表单,将用户分类为“A”代表管理员或“U”代表标准用户。

当您提交表单时,它应该写入我在 visual studio 中设置的数据库,该数据库目前已经有其他用户。

当我测试 Web 表单时,出现错误“NullReferenceException 未被用户代码处理”、“对象引用未设置为对象的实例”。它指向我的网络表单页面上的这一行代码。

clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.mdb"), Session["txtUserName"].ToString(), Session["txtPassword"].ToString(), Session["drpdwnlstSecurityLevel"].ToString());

你看到这行代码有什么问题吗?

我有一个标有“txtPassword”的文本框,一个标有“txtPassword”的文本框和一个标有“drpdwnlstSecurityLevel”的选项 U 或 A 的下拉列表。

当您提交信息时,它应该将其发送到我的 clsDataLayer.cs SaveUser 方法,该方法是:

public static bool SaveUser(string Database, string UserName, string UserPassword, string SecurityLevel)
    {

        bool userSaved;

        try
        {
            // Define SQLConnClass
            OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
                                                       "Data Source=" + Database);
            conn.Open();
            OleDbCommand command = conn.CreateCommand();
            string strSQL;

            // this insert data to user table
            strSQL = "Insert into tblUserLogin " +
                     "(UserName, UserPassword, SecurityLevel) values ('" +
                     UserName + "', '" + UserPassword + "', " + SecurityLevel + "')";

            // this gives a command to get or set values
            command.CommandType = CommandType.Text;
            command.CommandText = strSQL;

            // This sql statements brings out the affacted rows
            command.ExecuteNonQuery();

            // closes the connection
            conn.Close();
            userSaved = true;
        }

        catch (Exception ex)
        {
            userSaved = false;
        }

        return userSaved;
    }

当您尝试使用我的网络表单创建新用户时,它不会创建任何记录,只会发出我提到的错误。

这是我与这个问题相关的所有代码:

文件 clsDataLayer.cs:

//这个函数保存用户数据 public static bool SaveUser(字符串数据库,字符串用户名,字符串用户密码,字符串安全级别) {

bool userSaved;

try
{
    // Define SQLConnClass
    OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
                                               "Data Source=" + Database);
    conn.Open();
    OleDbCommand command = conn.CreateCommand();
    string strSQL;

    // this insert data to user table
    strSQL = "Insert into tblUserLogin " +
             "(UserName, UserPassword, SecurityLevel) values ('" +
             UserName + "', '" + UserPassword + "', " + SecurityLevel + "')";

    // this gives a command to get or set values
    command.CommandType = CommandType.Text;
    command.CommandText = strSQL;

    // This sql statements brings out the affacted rows
    command.ExecuteNonQuery();

    // closes the connection
    conn.Close();
    userSaved = true;
}

catch (Exception ex)
{
    userSaved = false;
}

return userSaved;

文件 frmManageUsers.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void btnAddUser_Click(object sender, EventArgs e)
    {
        string userName, userPassword;


        if (txtUserName.Text == "" || txtUserName.Text == null)
        {
            lblUserError.Text = ("User Name may not be empty");
            lblUserError.ForeColor = System.Drawing.Color.Red;
            return;
        }
        else

            userName = (txtUserName.Text);


        if (txtPassword.Text == "" || txtPassword.Text == null)
        {
            lblUserError.Text = ("Password may not be empty");
            lblUserError.ForeColor = System.Drawing.Color.Red;
            return;
        }
        else
        {
            userPassword = (txtPassword.Text);
        }

        // clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.mdb"), Session["txtUserName"].ToString(), Session["txtPassword"].ToString(), Session["drpdwnlstSecurityLevel"].ToString());
        clsDataLayer.SaveUser(
    Server.MapPath("PayrollSystem_DB.mdb"),
    txtUserName.Text,
    txtPassword.Text,
    drpdwnlstSecurityLevel.SelectedValue
    );
        Server.Transfer("frmManageUsers.aspx");        
    }
}

文件 frmManageUsers.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="frmManageUsers.aspx.cs" Inherits="frmManageUsers" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center">

        <a href="frmMain.aspx">
            <font color="black" size="2" style="text-align: center"><strong>
            <font color="blue" face="Comic Sans MS" size="4">Cool</font>
            <font color="#ff6600" face="Comic Sans MS" size="4">Biz</font>
            <font face="Comic Sans MS" size="4"> <font color="#993366">Productions</font>, 
            Inc.</font></strong></font>
        </a>
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Manage Users"></asp:Label>
        <br />
        <asp:Label ID="Label2" runat="server" Text="User Name: "></asp:Label>
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label3" runat="server" Text="Password: "></asp:Label>
        <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblUserError" runat="server"></asp:Label>
        <br />
        <asp:Label ID="Label4" runat="server" Text="Security Level: "></asp:Label>
        <asp:DropDownList ID="drpdwnlstSecurityLevel" runat="server" 
            DataSourceID="SqlDataSource2" DataTextField="SecurityLevel" 
            DataValueField="SecurityLevel">
            <asp:ListItem></asp:ListItem>
            <asp:ListItem></asp:ListItem>
        </asp:DropDownList>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
            ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>" 
            ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>" 
            SelectCommand="SELECT [SecurityLevel] FROM [tblUserLogin]">
        </asp:SqlDataSource>
        <br />
        <br />

        <asp:Button ID="btnAddUser" runat="server" onclick="btnAddUser_Click" 
            Text="Add User" />

        <br />
        <br />
        <asp:GridView ID="grdUserLogin" runat="server" AutoGenerateColumns="False" 
            DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="UserID" HeaderText="UserID" InsertVisible="False" 
                    SortExpression="UserID" />
                <asp:BoundField DataField="UserName" HeaderText="UserName" 
                    SortExpression="UserName" />
                <asp:BoundField DataField="UserPassword" HeaderText="UserPassword" 
                    SortExpression="UserPassword" />
                <asp:BoundField DataField="SecurityLevel" HeaderText="SecurityLevel" 
                    SortExpression="SecurityLevel" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:PayrollSystem_DBConnectionString %>" 
            InsertCommand="INSERT INTO [tblUserLogin] ([UserID], [UserName], [UserPassword], [SecurityLevel]) VALUES (?, ?, ?, ?)" 
            ProviderName="<%$ ConnectionStrings:PayrollSystem_DBConnectionString.ProviderName %>" 
            SelectCommand="SELECT * FROM [tblUserLogin]">
            <InsertParameters>
                <asp:Parameter Name="UserID" Type="Int32" />
                <asp:Parameter Name="UserName" Type="String" />
                <asp:Parameter Name="UserPassword" Type="String" />
                <asp:Parameter Name="SecurityLevel" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

最佳答案

您是否将这些值存储在 Session 中?如果您发布的代码在代码隐藏中,您应该能够直接访问这些值:

clsDataLayer.SaveUser(
    Server.MapPath("PayrollSystem_DB.mdb"), 
    txtUserName.Text, 
    txtPassword.Text, 
    drpdwnlstSecurityLevel.SelectedValue
    );

此外,您应该强烈考虑使用带参数的 SQL 而不是连接到 avoid SQL Injection :

strSQL = "Insert into tblUserLogin " +
         "(UserName, UserPassword, SecurityLevel) " + 
         "values (@UserName, @UserPassword, @SecurityLevel)";

同时,请同时执行以下操作:

  • 将您的 OleDbConnectionOleDbCommand 包装在 using block 中
  • 在您的catch block 中以某种方式显示异常消息,不要只返回false

关于c# - 无法写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751908/

相关文章:

MySQL 工作台。错误 1452 : Cannot add or update a child row: a foreign key constraint fails. 操作失败

c# - WCF 身份检查失败

c# - 密码框验证

c# - 通过 IEnumerable 进行分页

c# - session 状态在 Global.asax 的上下文中不可用

c# - 以编程方式构建 C# 解决方案

mysql - 如何查询 SQL 数据库以查找记录首次出现的日期?

c# - WCF 基本身份验证和自定义 token 身份验证

c# - 扩展方法 - 必须使用此关键字?

c# - 当 Microsoft SQL Server 中包含 html 标签时对列进行排序