【发布时间】:2011-09-24 16:01:05
【问题描述】:
我正在使用带有 ms-sql server 2008 express 的 asp.net 4 和 Visual Studio 2010。我使用了三种不同的方式将数据插入到数据库表中:
方式一:
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();
方式3:
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();
这三种方式中哪一种是网站中最优化的使用方式?
【问题讨论】:
-
取决于数据量(单个或批量)您还应该查看存储过程,因为这是我个人的选择
-
这三个都不是好的 - #2 和 #3 特别糟糕。您应该检查参数化查询,而不是将您的 SQL 语句连接在一起 - 这是一种不好的做法,并为 SQL 注入攻击打开了大门。
-
检查以下内容:stackoverflow.com/questions/2149897/… 简而言之,看看 SQL Server Bulk Insert。如果您有大量数据,速度会非常快
标签: c# asp.net sql sql-server