【问题标题】:ASP.NET - Unable to insert data into databaseASP.NET - 无法将数据插入数据库
【发布时间】:2021-07-23 17:55:17
【问题描述】:

我知道连接字符串不是问题,因为我可以很好地从数据库中读取数据,但我不知道为什么我不能将数据插入数据库。

.aspx 文件

<div class="column one-second">
  <asp:TextBox placeholder="Your name" type="text" name="name" id="namelbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>

<div class="column one-second">
  <asp:TextBox placeholder="location" type="text" name="location" id="LocationLbl" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
  <asp:TextBox placeholder="Body" type="text" name="text" id="TextLBL" size="40" aria-required="true" aria-invalid="false" runat="server"></asp:TextBox>
</div>
<div class="column one">
  <asp:FileUpload id="FileUpload1" runat="server"> </asp:FileUpload>

  <asp:Label ID="lblmessage" runat="server" />
</div>
<div class="column one">
  <asp:Button id="submit" Text="Submit" runat="server" OnClick="submit_Click"> </asp:Button>
</div> 

C# 函数

protected void submit_Click(object sender, EventArgs e)
{
    Console.WriteLine("BUTTON CLICKED");
    string constr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        string query = "INSERT INTO blo(Title, post, location) VALUES (@Title, @post, @location)";
        using (MySqlCommand cmd = new MySqlCommand(query))
        {
            cmd.Connection = con;

            string title = namelbl.Text;
            Console.WriteLine(title);
            cmd.Parameters.AddWithValue("Title", title);
            string post = TextLBL.Text;
            cmd.Parameters.AddWithValue("post", post);
            string location = LocationLbl.Text;
            cmd.Parameters.AddWithValue("location", location);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

【问题讨论】:

  • 错误是什么? “INSERT INTO blo”应该是“INSERT INTO blog”吗?

标签: c# mysql asp.net ado.net


【解决方案1】:

由于您在.AddWithValue() 中输入错误的参数名称,您的查询无法正常工作。

cmd.Parameters.AddWithValue("Title", title);
cmd.Parameters.AddWithValue("post", post);
cmd.Parameters.AddWithValue("location", location);

正确的做法应该是:

cmd.Parameters.AddWithValue("@Title", title);
cmd.Parameters.AddWithValue("@post", post);
cmd.Parameters.AddWithValue("@location", location);

建议

1. 建议不要使用`.AddWithValue()`作为本[文章]中提到的关注点(https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-使用-addwithvalue-already/)。请确保您需要传递与 `SqlParameter` 中的相应表列匹配的**精确数据类型和长度**的值。
cmd.Parameters.Add("@Param", <<MySqlDbType>>, <<Length>>).Value = value;
  1. 当您为 MySqlConnectionMySqlCommand 应用块时,您不必手动调用 con.Close(),因为这些 IDisposable 对象将自动处置资源和连接,如 article 中所述。

  2. (可选) 添加try catch 块并从ExecuteNonQuery() 获取值,用于验证记录是否已插入数据库并进行异常处理。

  • 异常处理将有助于调试和处理执行期间遇到的异常。同时,您可以提供有意义的错误信息来通知用户。

  • ExecuteNonQuery()能返回值说明

受影响的行数。

  • 因此,这对于返回有用的消息来通知记录是否成功插入/更新到数据库中也很有用。

最后,你的代码应该是:

try
{
    using (MySqlConnection con = new MySqlConnection(constr))
    {
        string query = "INSERT INTO blo(Title, post, location) VALUES (@Title, @Post, @Location)";
        using (MySqlCommand cmd = new MySqlCommand(query))
        {
            cmd.Connection = con;

            string title = namelbl.Text;
            Console.WriteLine(title);
            cmd.Parameters.AddWithValue("@Title", title);
        
            string post = TextLBL.Text;
            cmd.Parameters.AddWithValue("@Post", post);

            string location = LocationLbl.Text;
            cmd.Parameters.AddWithValue("@Location", location);
        
            con.Open();
            var recordAffected = (int)cmd.ExecuteNonQuery();

            if (recordAffected > 0)
            {
                // Record successfully inserted case
            }
            else
            {
                // Record fail inserted case
            }
        }
    }
}
catch (Exception ex)
{
    // Handling exception
}

已编辑: 非常感谢并感谢@BradleyGrainger 提供的评论,我有“删除线”建议1,因为Can We Stop Using .AddWithValue() 中提到的问题由MySql 处理。

Start Using AddWithValue

可以使用 AddWithValue 的主要原因是 MySQL 的文本协议没有以对客户端类型推断很重要的方式键入。

【讨论】:

  • 对 MySQL 使用 AddWithValue 完全没问题:mysqlconnector.net/overview/using-addwithvalue。实际上,您应该避免将SqlDbType 与MySqlConnector 一起使用;这些是SqlClient (MS SQL Server) 的类型。
  • 嗨@BradleyGrainger,感谢您的建议和文章。我将根据文章更新解决方案。再次非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-11-21
  • 2012-04-13
  • 1970-01-01
  • 2013-03-02
  • 2017-10-24
相关资源
最近更新 更多