[英]Adding data to a database using C# in asp.net
我需要使用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();
}
}
}
我將從string.format開始只是為了看看我們在哪里...
string.format("insert into Company values('{0}','{1}')", txtProductName.Text,
txtProductPrice.Text);
您不應在查詢中直接引用文本字段,而應使用參數化的輸入來避免注入。 它使任何人都無法發送自己可執行的代碼/ sql。
查看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);
}
}
}
這是一個安全問題。 就您當前的代碼而言; 請附上錯誤消息/它在哪里中斷。 正如其他人先前所說,如果您要在SQL服務器上輸入數據的列不按順序排列和/或列的數量比要向其中插入值的列多,則需要先告訴服務器您要在其中輸入哪些列將值插入。
這看起來類似於:
"INSERT Region (RegionID, RegionDescription) VALUES (5, 'NorthWestern')";
在您當前的代碼中將是這樣的:
cmd.CommandText = "insert into Company (Product_Name, Product_Price) VALUES ('"+txtProductName.Text+"','"+txtProductPrice.Text+"')";
通過了這兩項,我們真的需要更多信息!
就您的數據而言,為什么要在公司記錄中插入產品信息? 除非您要執行的操作有特定的用例,否則您應該考慮規范化和創建產品表以存儲該信息。
您的SQL語法可能有問題,您確定Company表中只有這兩列嗎? 如果不是,則需要指定列名,否則SQL語句將失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.