Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c# - Data Adapter Vs Sql Command

Which one would be better in executing an insert statement for ms-sql database:

Sql DataAdapter or SQL Command Object?

Which of them would be better, while inserting only one row and while inserting multiple rows?

A simple example of code usage:

SQL Command

string query = "insert into Table1(col1,col2,col3) values (@value1,@value2,@value3)";
int i;

SqlCommand cmd = new SqlCommand(query, connection);
// add parameters...
cmd.Parameters.Add("@value1",SqlDbType.VarChar).Value=txtBox1.Text;
cmd.Parameters.Add("@value2",SqlDbType.VarChar).Value=txtBox2.Text;
cmd.Parameters.Add("@value3",SqlDbType.VarChar).Value=txtBox3.Text;
cmd.con.open();
i = cmd.ExecuteNonQuery();
cmd.con.close();

SQL Data Adapter

DataRow dr = dsTab.Tables["Table1"].NewRow();
DataSet dsTab = new DataSet("Table1");
SqlDataAdapter adp = new SqlDataAdapter("Select * from Table1", connection);
adp.Fill(dsTab, "Table1");
dr["col1"] = txtBox1.Text;
dr["col2"] = txtBox5.Text;    
dr["col3"] = "text";

dsTab.Tables["Table1"].Rows.Add(dr);

SqlCommandBuilder projectBuilder = new SqlCommandBuilder(adp);
DataSet newSet = dsTab.GetChanges(DataRowState.Added);
adp.Update(newSet, "Table1");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Updating a data source is much easier using DataAdapters. It's easier to make changes since you just have to modify the DataSet and call Update.

There is probably no (or very little) difference in the performance between using DataAdapters vs Commands. DataAdapters internally use Connection and Command objects and execute the Commands to perform the actions (such as Fill and Update) that you tell them to do, so it's pretty much the same as using only Command objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...