简体   繁体   English

在ASP.NET中使用C#将数据添加到数据库

[英]Adding data to a database using C# in asp.net

I need to add things to my database using a txtbox and a button (btnAdd) this is my code, but the CommandType.Text; 我需要使用txtbox和按钮(btnAdd)将东西添加到数据库中,这是我的代码,但是CommandType.Text; part has an error and I can't fix it. 部分有错误,我无法修复。

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;

namespace _21542890_F
{
     public partial class Add_Product : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dylan\Documents\Company.mdf;Integrated Security=True;Connect Timeout=30");
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void lbtnHome_Click(object sender, EventArgs e)
        {
            Response.Redirect("Home Page.aspx");
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into Company values('"+txtProductName.Text+"','"+txtProductPrice.Text+"')";
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

I would start with a string.format just to see where we are... 我将从string.format开始只是为了看看我们在哪里...

string.format("insert into Company values('{0}','{1}')", txtProductName.Text,
txtProductPrice.Text);

You shouldn't be referencing text fields directly in your query, but instead using paramaterized inputs to avoid injection. 您不应在查询中直接引用文本字段,而应使用参数化的输入来避免注入。 It keeps anyone from sending code/sql that is executable by itself. 它使任何人都无法发送自己可执行的代码/ sql。

Look into this example from Microsoft: 查看Microsoft的以下示例:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

It's a security issue. 这是一个安全问题。 As far as your code currently; 就您当前的代码而言; please include an error message/where it is breaking. 请附上错误消息/它在哪里中断。 As others have previous stated, if the columns you're inputting data into on your SQL server are not in order and/or there are more columns than you're inserting values into, you need to first tell the server which columns you're inserting values into. 正如其他人先前所说,如果您要在SQL服务器上输入数据的列不按顺序排列和/或列的数量比要向其中插入值的列多,则需要先告诉服务器您要在其中输入哪些列将值插入。

This looks similar to: 这看起来类似于:

"INSERT Region (RegionID, RegionDescription) VALUES (5, 'NorthWestern')";

In your current code it would be this: 在您当前的代码中将是这样的:

cmd.CommandText = "insert into Company (Product_Name, Product_Price)  VALUES ('"+txtProductName.Text+"','"+txtProductPrice.Text+"')";

Passed those two items, we really need more information! 通过了这两项,我们真的需要更多信息!

As far as your data goes though, why are you inserting product information into a company record? 就您的数据而言,为什么要在公司记录中插入产品信息? Unless there is a specific use case to what you're doing, you should think about normalizing and creating a product table to store that information in. 除非您要执行的操作有特定的用例,否则您应该考虑规范化和创建产品表以存储该信息。

It may be problem with your SQL syntax, are you sure you have only those two columns inside Company table? 您的SQL语法可能有问题,您确定Company表中只有这两列吗? If not, you need to specify column names, otherwise SQL statement will fail. 如果不是,则需要指定列名,否则SQL语句将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM