【问题标题】:Adding data to a database using C# in asp.net在 asp.net 中使用 C# 将数据添加到数据库
【发布时间】:2015-12-12 02:37:11
【问题描述】:

我需要使用 txtbox 和按钮 (btnAdd) 将内容添加到我的数据库 这是我的代码,但是 CommandType.Text;部分有错误,我无法修复它。

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();
        }
    }
}

【问题讨论】:

  • 请发布您的构建/运行时错误
  • 发布Company 表的架构。

标签: c# mysql asp.net sqlconnection sqlcommand


【解决方案1】:

我会从 string.format 开始,只是为了看看我们在哪里......

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

【讨论】:

    【解决方案2】:

    您不应在查询中直接引用文本字段,而应使用参数化输入来避免注入。它可以防止任何人发送可自行执行的代码/sql。

    看看这个来自微软的例子:

    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);
            }
        }
    }
    

    这是一个安全问题。就您目前的代码而言;请包括一条错误消息/它在哪里中断。正如其他人之前所说,如果您在 SQL 服务器上输入数据的列不按顺序排列和/或列数多于您要插入的值,您需要首先告诉服务器您是哪些列将值插入。

    这看起来类似于:

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

    在您当前的代码中是这样的:

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

    通过了这两项,我们真的需要更多信息!

    就您的数据而言,您为什么要将产品信息插入公司记录?除非您正在做的事情有特定的用例,否则您应该考虑规范化并创建一个产品表来存储该信息。

    【讨论】:

      【解决方案3】:

      您的 SQL 语法可能有问题,您确定 Company 表中只有这两列吗?如果没有,则需要指定列名,否则SQL语句会失败。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-27
        • 2016-07-04
        • 2018-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多