【问题标题】:Insert Text from Textbox Into Database [duplicate]将文本框中的文本插入数据库[重复]
【发布时间】:2013-12-11 19:45:08
【问题描述】:

我正在尝试将用户从我的文本框中输入的值/文本添加到我的数据库中。

目前我无法获取将值插入到 sqldatabase 的代码。

这是我的 aspx 代码

<asp:TextBox ID="txt_WineName" runat="server" PlaceHolder="WineName" />
<asp:TextBox ID="txt_WineYear" runat="server" PlaceHolder="WineYear" />
<asp:TextBox ID="txt_WinePrice" runat="server" PlaceHolder="WinePrice" />
<asp:TextBox ID="txt_WineType" runat="server" PlaceHolder="WineType" />
<asp:Button ID="btn_AddWine" runat="server" Text="Add" />

这是我的 C# 代码:

protected void btn_AddWine(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection("Data Source=PCM13812;Initial Catalog=Kronhjorten;Integrated Security=True"))
    {
        connection.Open();
        string query = "SELECT * FROM Wines";
        using (SqlCommand command = new SqlCommand(query, connection))
        { 
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read()) 
                {
                    string Name = txt_WineName.Text;
                    string Year = txt_WineYear.Text;
                    string Price = txt_WinePrice.Text;
                    string Type = txt_WineType.Text;
                    Sql_Insert.Insert();
                }
            }
        }
    }
}

我尝试了 stackoverflow 中的其他链接,但似乎找不到任何可以实现此功能的链接。

希望你能帮助我。如果我以一种奇怪的方式这样做,我很抱歉。

【问题讨论】:

    标签: c# asp.net sql


    【解决方案1】:

    正确的命令:

    首先,您使用的是SqlDataReader。这不是用于将数据插入数据库,而是用于从中读取数据。你必须执行你正在使用的SqlCommand

    string query = "YOUR_QUERY_HERE";
    
    using (SqlConnection connection = new SqlConnection("Data Source=PCM13812;Initial Catalog=Kronhjorten;Integrated Security=True"))
    {
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            connection.Open(); 
            command.ExecuteNonQuery();
        }
    }
    

    正确查询:

    当你做对了,是时候写一个正确的查询了。你的以SELECT 开头,这也是用于检索数据,而不是插入。您的查询应使用 INSERT 并应如下所示:

    string name = txt_WineName.Text;
    string year = txt_WineYear.Text;
    string price = txt_WinePrice.Text;
    string type = txt_WineType.Text;
    
    string query = "INSERT INTO Wines(Name, Year, Price, Type) " +
                   "Values('" + name + "', '" + year + "', '" + price + "', '" + type + "')";
    

    参数/验证:

    我提供的代码仅用作演示,而不是工作代码。您应该始终验证用户输入并使用参数化查询。更多信息/阅读:

    【讨论】:

      【解决方案2】:

      您正在使用SqlDataReader,它只是从数据库中读取数据而不是插入/更新。 以下链接可能对您有所帮助

      Insert Data into database in C#

      How to insert Records in Database using C# language?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-05
        • 2012-01-20
        • 2013-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-24
        • 2015-03-10
        相关资源
        最近更新 更多