【问题标题】:Error when trying to connect web form to SQL database to insert values尝试将 Web 表单连接到 SQL 数据库以插入值时出错
【发布时间】:2021-09-23 16:44:24
【问题描述】:

我正在尝试将我的 ASP.NET Web 表单连接到我创建的 SQL 数据库(名称为 User)并将值添加到表 User。但是,出现运行时错误,显示“System.Data.SqlClient.SqlException:'关键字 USER 附近的语法不正确。'”我不知道问题所在。是语法吗?请帮忙看看我下面的代码。这是 .aspx.cs 代码。

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.Configuration;  
  
namespace BMICalc
{  
    public partial class WebForm2 : System.Web.UI.Page  
    {  
        protected void Page_Load(object sender, EventArgs e)  
        {  
           if(IsPostBack)  
            {  
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString);  
                conn.Open();  
                string checkuser = "select count(*) from USER where emailAddress='"+ TextBox3.Text+"'";
                SqlCommand cmd = new SqlCommand(checkuser, conn);  
                int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());  
  
                if (temp == 1)  
                {  
                    Response.Write("Account Already Exists");  
                }  
  
                conn.Close();  
            }  
               
            }  
  
        protected void Button1_Click(object sender, EventArgs e)  
        {  
            try  
            {  
  
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegiConnectionString"].ConnectionString);  
                conn.Open();  
                string insertQuery = "insert into User(firstName,lastName,emailAddress,password)values (@firstName,@lastName,@emailAddress,@password)";  
                SqlCommand cmd = new SqlCommand(insertQuery, conn);  
                cmd.Parameters.AddWithValue("@firstName", TextBox1.Text);  
                cmd.Parameters.AddWithValue("@lastName", TextBox2.Text);  
                cmd.Parameters.AddWithValue("@emailAddress", TextBox3.Text);  
                cmd.Parameters.AddWithValue("@password", TextBox4.Text);  
                cmd.ExecuteNonQuery();  
  
                Response.Write("User is successfully registered!");  
  
                conn.Close();  
  
            }  
            catch (Exception ex)  
            {  
                Response.Write("error" + ex.ToString());  
            }  
        }  
    }  
} 

谢谢。

【问题讨论】:

  • 你使用的不是mysql连接器是sql server
  • 原始错误中的关键字xxx是什么?
  • 哦,我的错,是用户。我现在已经编辑了。
  • 在单词之间放置 gups" 用户 (firstName , lastName , emailAddress , password) 值"
  • 此外,您似乎正在使用未经处理的文本框值创建 SELECT 语句。这就是 SQL 注入的发生方式。您应该使用参数,而不是将字符串与用户输入连接

标签: c# sql asp.net database webforms


【解决方案1】:

错误是指keyword 'USER'。您打算将 User 用作表的名称,而不是关键字。尝试逃避它:

insert into [User] (firstName,lastName,emailAddress,password)
values (@firstName,@lastName,@emailAddress,@password)

正如 Devlin 所指出的,select 语句也有一个未转义的USER

select count(*) from [USER] where emailAddress='"+ TextBox3.Text+"'"

【讨论】:

  • SELECT 语句呢?
【解决方案2】:

问题很可能是一个或多个 TextBox 值为 null 或空。当值为 null 或为空时,需要将值设置为 DBNull.Value。

下面的代码展示了如何执行错误处理以显示错误消息以及如何使用参数。代码已经过测试,但是代码没有加密密码——我将把它留给你来实现。在将密码存储到数据库之前对密码进行加密非常重要。

您需要为您的环境更改“connectionStr”的值。请参阅Connection Strings 了解更多信息。下面的代码已经过 SQL Server Express 测试。

尝试以下方法:

VS 2019

创建一个新的 ASP.NET Web 应用程序 (.NET Framework)

  • 项目名称:BMICalc
  • 点击创建
  • 点击清空
  • 点击创建

添加网络表单

  • 在VS菜单中,点击Project
  • 选择Web表单(名称:WebForm2.aspx)

WebForm2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="BMICalc.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblUserId" runat="server" Text="UserId:" style="top: 50px; left: 150px; position: absolute; height: 19px; width: 213px"></asp:Label>
            <asp:TextBox ID="textBoxUserId" runat="server" Height="336px" TextMode="SingleLine" style="top: 48px; left: 354px; position: absolute; height: 22px; width: 225px"></asp:TextBox>

            <asp:Label ID="lblFirstName" runat="server" Text="First Name:" style="top: 90px; left: 150px; position: absolute; height: 19px; width: 213px"></asp:Label>
            <asp:TextBox ID="textBoxFirstName" runat="server" Height="336px" TextMode="SingleLine" style="top: 88px; left: 354px; position: absolute; height: 22px; width: 225px"></asp:TextBox>

             <asp:Label ID="lblLastName" runat="server" Text="Last Name:" style="top: 130px; left: 150px; position: absolute; height: 19px; width: 213px"></asp:Label>
            <asp:TextBox ID="textBoxLastName" runat="server" Height="336px" TextMode="SingleLine" style="top: 128px; left: 354px; position: absolute; height: 22px; width: 225px"></asp:TextBox>

             <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address:" style="top: 170px; left: 150px; position: absolute; height: 19px; width: 213px"></asp:Label>
           <asp:TextBox ID="textBoxEmailAddress" runat="server" Height="336px" TextMode="SingleLine" style="top: 168px; left: 354px; position: absolute; height: 22px; width: 225px"></asp:TextBox>

             <asp:Label ID="lblPassword" runat="server" Text="Password:" style="top: 210px; left: 150px; position: absolute; height: 19px; width: 213px"></asp:Label>
            <asp:TextBox ID="textBoxPassword" runat="server" Height="336px" TextMode="Password" style="top: 208px; left: 354px; position: absolute; height: 22px; width: 225px"></asp:TextBox>
        </div>
        <div>
            <asp:Button ID="btnCreateUser" runat="server" Text="Create User" OnClick="btnCreateUser_Click" style="top: 260px; left: 425px; position: absolute; height: 35px; width: 100px" />
        </div>
        <div>
             <asp:Label ID="lblMsg" runat="server" Text="" style="top: 330px; left: 150px; position: absolute; height: 19px; align-content:center; color:red"></asp:Label>
        </div>
    </form>
</body>
</html>

WebForm2.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;

namespace BMICalc
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        private string connectionStr = String.Format(@"Data Source='.\SQLExpress'; Initial Catalog='BMICalc'; Integrated Security=True; MultipleActiveResultSets=True");
        private string logFilename = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string errMsg = string.Empty;
            string folderPath = Path.GetDirectoryName(HttpContext.Current.Server.MapPath("~"));
            logFilename = Path.Combine(folderPath, "log.txt");

            //lblMsg.Text = "logFilename: " + logFilename;

            if (IsPostBack)
            {
                try
                {
                    int rowCount = CheckUser(textBoxEmailAddress.Text);

                    if (rowCount > 0)
                    {
                        lblMsg.Text = "Account already exists.";
                    }
                }
                catch(SqlException ex)
                {
                    errMsg = "Error: (Page_Load - SqlException): " + ex.Message;
                    LogMsg(errMsg);
                    lblMsg.Text = errMsg;

                    //uncommenting the following line may be helpful for debugging purposes
                    //throw ex;
                }
                catch (Exception ex)
                {
                    errMsg = "Error: (Page_Load): " + ex.Message;
                    LogMsg(errMsg);
                    lblMsg.Text = errMsg;

                    //uncommenting the following line may be helpful for debugging purposes
                    //throw ex;
                }
            }
        }

        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            string errMsg = string.Empty;

            try
            {
                int rowCount = AddUser(textBoxUserId.Text, textBoxFirstName.Text, textBoxLastName.Text, textBoxEmailAddress.Text, textBoxPassword.Text);

                if (rowCount > 0)
                {
                    lblMsg.Text = "User successfully registered.";
                }
                else
                {
                    lblMsg.Text = "Registration failed.";
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                //ToDo: log error message
                errMsg = "Error: (btnCreateUser - SqlException): " + ex.Message;
                LogMsg(errMsg);
                lblMsg.Text = errMsg;

                //uncommenting the following line may be helpful for debugging purposes
                //throw ex; 
            }
            catch (Exception ex)
            {
                //ToDo: log error message
                errMsg = "Error: (btnCreateUser): " + ex.Message;
                LogMsg(errMsg);
                lblMsg.Text = errMsg;

                //uncommenting the following line may be helpful for debugging purposes
                //throw ex;
            }
        }

        private int AddUser(string userId, string firstName, string lastName, string emailAddress, string password)
        {
            int rowCount = 0;

            string sqlText = "insert into [User] (UserId, FirstName, LastName, EmailAddress, Password) values (@userId, @firstName, @lastName, @emailAddress, @password)";

            using (SqlConnection cn = new SqlConnection(connectionStr))
            {
                //open
                cn.Open();

                using (SqlCommand cmd = new SqlCommand(sqlText, cn))
                {
                    //if a value is null, it's necessary to use DBNull.Value

                    //userId
                    if (!String.IsNullOrEmpty(userId))
                    {
                        cmd.Parameters.Add("@userId", SqlDbType.NVarChar).Value = userId;
                    }
                    else
                    {
                        cmd.Parameters.Add("@userId", SqlDbType.NVarChar).Value = DBNull.Value;
                    }

                    //firstName
                    if (!String.IsNullOrEmpty(firstName))
                    {
                        cmd.Parameters.Add("@firstName", SqlDbType.NVarChar).Value = firstName;
                    }
                    else
                    {
                        cmd.Parameters.Add("@firstName", SqlDbType.NVarChar).Value = DBNull.Value;
                    }

                    //lastName
                    if (!String.IsNullOrEmpty(lastName))
                    {
                        cmd.Parameters.Add("@lastName", SqlDbType.NVarChar).Value = lastName;
                    }
                    else
                    {
                        cmd.Parameters.Add("@lastName", SqlDbType.NVarChar).Value = DBNull.Value;
                    }

                    //emailAddress
                    if (!String.IsNullOrEmpty(emailAddress))
                    {
                        cmd.Parameters.Add("@emailAddress", SqlDbType.NVarChar).Value = emailAddress;
                    }
                    else
                    {
                        cmd.Parameters.Add("@emailAddress", SqlDbType.NVarChar).Value = DBNull.Value;
                    }

                    //password
                    if (!String.IsNullOrEmpty(password))
                    {
                        cmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = password;
                    }
                    else
                    {
                        cmd.Parameters.Add("@password", SqlDbType.NVarChar).Value = DBNull.Value;
                    }

                    //execute; returns the number of rows affected
                    rowCount = cmd.ExecuteNonQuery();
                }
            }

            return rowCount;

        }

        private int CheckUser(string emailAddress)
        {
            int rowCount = 0;

            string sqlText = "select count(*) from [User] where emailAddress= @emailAddress";

            using (SqlConnection cn = new SqlConnection(connectionStr))
            {
                //open
                cn.Open();

                using (SqlCommand cmd = new SqlCommand(sqlText, cn))
                {
                    //if a value is null, it's necessary to use DBNull.Value
                    if (!String.IsNullOrEmpty(emailAddress))
                    {
                        cmd.Parameters.Add("@emailAddress", SqlDbType.NVarChar).Value = emailAddress;
                    }
                    else
                    {
                        cmd.Parameters.Add("@emailAddress", SqlDbType.NVarChar).Value = DBNull.Value;
                    }

                    //execute and try to convert
                    Int32.TryParse(cmd.ExecuteScalar().ToString(), out rowCount);
                }
            }

            return rowCount;
        }

        public int ExecuteNonQuery(string sqlText)
        {
            int rowCount = 0;
            using (SqlConnection con = new SqlConnection(connectionStr))
            {
                //open
                con.Open();

                using (SqlCommand cmd = new SqlCommand(sqlText, con))
                {
                    //execute; return num rows affected
                    rowCount = cmd.ExecuteNonQuery();
                }
            }

            return rowCount;
        }

        private void LogMsg(string msg)
        {
            //ToDo: replace the code below with desired code
            //this code is for debugging and it doesn't trim the log
            string formattedMsg = String.Format("{0} {1} {2}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), msg.Replace(System.Environment.NewLine, " "), System.Environment.NewLine);
            File.AppendAllText(logFilename, formattedMsg);
        }
    }
}

创建数据库表的代码如下:

CREATE TABLE [dbo].[User]([UserId] [nvarchar](50) Not NULL, 
                          [FirstName] [nvarchar](75) NULL, 
                          [LastName] [nvarchar](75) NULL, 
                          [EmailAddress] [nvarchar](75) NULL, 
                          [Password] [nvarchar](75) NULL,  
                          CONSTRAINT [PK_User_UserId] PRIMARY KEY(UserId));

资源

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2014-06-09
    相关资源
    最近更新 更多