c# - 可以选择但不能插入数据库 mysql C# ASP.NET

标签 c# mysql asp.net sql-insert

我连接到我的数据库,我可以毫无问题地检索数据,但我无法插入。警报也没有显示,所以我确定查询没有被执行,它只是重定向到 aspx 页面。我尝试了许多不同的解决方案,但我认为问题不在我正在寻找的地方。这是代码,希望有人能提供帮助。

代码隐藏:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Threading;
using System.Threading.Tasks;

namespace Childrens.Admin
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void btnViewStaff_ServerClick(object sender, EventArgs e)
    {
        divAddStaff.Visible = false;
        staffGridView.Visible = true;
    }

    protected void btnAddNewStaff_ServerClick(object sender, EventArgs e)
    {
        staffGridView.Visible = false;
        divAddStaff.Visible = true;
    }

    protected void btnSubmitStaff_ServerClick(object sender, EventArgs e)
    {
        if (txtPassword == txtCPassword)
        {
            using (SqlConnection addStaffConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConn"].ToString()))
            {
                try
                {
                    addStaffConn.Open();

                    string query = "INSERT INTO [Staff] (staff_fname,staff_sname,staff_email,staff_pass) VALUES ('" + txtFName + "','" + txtSName + "','" + txtEmail + "','" + txtPassword+"')"; //(@fname,@sname,@email,@pass)";
                    SqlDataAdapter staffAdapter = new SqlDataAdapter();
                    SqlCommand addStaffCommand = new SqlCommand(query, addStaffConn);

                    /*addStaffCommand.Parameters.AddWithValue("@fname", txtFName);
                    addStaffCommand.Parameters.AddWithValue("@sname", txtSName);
                    addStaffCommand.Parameters.AddWithValue("@email", txtEmail);
                    addStaffCommand.Parameters.AddWithValue("@pass", txtPassword);*/
                    staffAdapter.InsertCommand = addStaffCommand;
                    staffAdapter.InsertCommand.ExecuteNonQuery();


                    addStaffConn.Close();
                    Response.Write(String.Format("<script>alert('The entry was successful!');window.location='{0}';</script>", "URL=staff.aspx"));

                }
                catch (Exception ex)
                {
                    Response.Write(String.Format("<script>alert('The entry was successful!');window.location='{0}';</script>", "URL=staff.aspx"));
                }
                finally
                {
                    if (addStaffConn.State == System.Data.ConnectionState.Open)
                    {
                        addStaffConn.Close();
                    }
                    addStaffConn.Dispose();
                }
            }
        }
    }
}
}

web.config 文件:

<?xml version="1.0" encoding="utf-8"?>

<!--
For more information on how to configure your ASP.NET application, please 
visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.codedom>
<compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
    type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, 
   Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, 
Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 
/define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
</compilers>
</system.codedom>
<connectionStrings>
<add name="myConn" connectionString="server=localhost;user 
id=root;persistsecurityinfo=True;database=childrens" />
<add name="childrensConnectionString" 
connectionString="server=localhost;user id=root;password=password;persistsecurityinfo=True;database=childrens;allowuservariables=True"
    providerName="MySql.Data.MySqlClient" />
 </connectionStrings>

 </configuration>

最佳答案

你应该使用 MySQL 的 .Net Connector ,而不是用于 MS SQL Server 的库。此外,数据适配器往往更多地用于数据表和类似的东西;根据您的需要,只需执行“命令”对象就足够了。

每个人都提到的安全漏洞是您的查询(充其量)打破了第二个“fname”、“sname”等...包含一个或多个撇号;您应该研究参数化查询以避免此类问题。

编辑:此外,[] 是 Microsoft 数据库(MS SQL Server 和 MS Access)的字段分隔符; `(在 ~ 键上)由 MySQL 使用。

编辑#2:漏洞示例:

INSERT INTO [Staff] (staff_fname,staff_sname,staff_email,staff_pass) VALUES ('"+ txtFName + "','"+ txtSName + "','"+ txtEmail + "','"+ txtPassword+ "')"

用户输入他们的名字 O','','','then'), ('they', 'can', 'add', 'multiple'), (' users','or','possibly','worse'), ('without','even','causing','an'), ('error

关于c# - 可以选择但不能插入数据库 mysql C# ASP.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49866371/

相关文章:

c# - 将 double 显式转换为具有不同结果的 int

C# 将字符串变量转换为 FormattableString

mysql - 在 sql 查询中使用 JOIN 或在查询中使用存储函数,哪个更好?

php - 如何扩展从 MySQL 导入的类别列表

c# - Telerik Rad Combo Box 以及如何使其失去焦点

c# - 跨线程使用不同安全协议(protocol)的 .NET https 请求

asp.net - IIS 6 不显示默认文档 (default.aspx)

c# - IIS中回收应用程序池时,是否调用了Application_End?

c# - udpclient可以同时是组播和单播吗

python - 在 macOS High Sierra 上安装 mysql-python