gpt4 book ai didi

c# - 在 asp.net c# 中优化数据库中的插入过程

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:33 25 4
gpt4 key购买 nike

我正在使用 asp.net 4 和 visual studio 2010 以及 ms-sql server 2008 express。我使用了三种不同的方式将数据插入数据库表:

方式一:

    DataSet dsTab = new DataSet("Table1");
SqlDataAdapter adp = new SqlDataAdapter("Select * from Table1", con);
adp.Fill(dsTab, "Table1");

DataRow dr = dsTab.Tables["Table1"].NewRow();
dr["col1"] = txtBox1.Text;
dr["col2"] = txtBox5.Text;
dr["col3"] = User.Identity.Name.ToString();
dr["col4"] = "text";
dr["col5"] = DateTime.Now;
dr["col6"] = txtBox3.Text;
dr["col7"] = txtBox2.Text;
dsTab.Tables["Table1"].Rows.Add(dr);

SqlCommandBuilder projectBuilder = new SqlCommandBuilder(adp);
DataSet newSet = dsTab.GetChanges(DataRowState.Added);
adp.Update(newSet, "Table1");

方式二:

SqlDataAdapter AdapterMessage = new SqlDataAdapter();
AdapterMessage.InsertCommand = new SqlCommand();
AdapterMessage.InsertCommand.Connection = con;
AdapterMessage.InsertCommand.CommandText = "insert into Table1(col1,col2,col3,col4,col5,col6,col7) values ('" + txtBox1.Text + "','" + txtBox5.Text + "','" + User.Identity.Name.ToString(); + "','text','" + DateTime.Now + "','" + txtBox3.Text + "','" + txtBox2.Text + "')";
AdapterMessage.InsertCommand.ExecuteNonQuery();
AdapterMessage.Dispose();

方式三:

string query = "insert into Table1(col1,col2,col3,col4,col5,col6,col7) values ('" + txtBox1.Text + "','" + txtBox5.Text + "','" + User.Identity.Name.ToString(); + "','text','" + DateTime.Now + "','" + txtBox3.Text + "','" + txtBox2.Text + "')";
int i;

SqlCommand cmd = new SqlCommand(query);
con.open();
i = cmd.ExecuteNonQuery();
con.close();

这三种方式中哪一种是最优化的网站使用方式??

最佳答案

您展示的唯一不受 SQL 注入(inject)攻击影响的示例是 #1。

由于其他两个容易受到攻击,#1 是您唯一的选择(在您提供的三个选项中)。返回检查您的代码并立即修复#2 或#3 的任何示例。否则,您的网站将遭到黑客攻击。

您是否发现尝试过的各种方法之间存在性能问题?否则,您最好花时间保护您的网站,而不是过度设计您的代码。

看看 SqlParameter class .这是向 SQL Server 提交参数化查询的正确方法,并在正确使用时消除 SQL 注入(inject)攻击的可能性。

也就是说,如果这是我的代码,我将不会使用任何这些选项。这是对我来说最好的方法的伪代码:

using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);

//add parameters here

command.Connection.Open();
command.ExecuteNonQuery();
}

关于c# - 在 asp.net c# 中优化数据库中的插入过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6512874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com