将文本框中的文本插入数据库

Car*_*sen 1 c# sql asp.net

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

目前我无法获取将值插入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" />
Run Code Online (Sandbox Code Playgroud)

这是我的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();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了stackoverflow的其他链接,但似乎找不到任何使这项工作的东西.

希望您能够帮助我.如果我以一种奇怪的方式做这件事,我很抱歉.

Abb*_*bas 5

正确的命令:

首先,你正在使用一个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

正确的查询:

当你做对了,是时候写一个正确的查询了.你的开头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 + "')";
Run Code Online (Sandbox Code Playgroud)

参数/验证:

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