有人可以解释为什么在以下代码中使用了SqlDataAdapter
吗?没有这个适配器,代码工作正常。
另外,为什么我们使用DataAdapter
?请帮助我理解DataAdapter
这种用法。
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.....\\SQLEXPRESS;Initial Catalog=......;Integrated Security=True");
con.Open();
SqlDataAdapter da =new SqlDataAdapter(); // Why use `SqlDataAdapter` here?
SqlCommand sc = new SqlCommand("insert into bhargavc values(" + textBox1.Text + "," + textBox2.Text + ");", con);
var o = sc.ExecuteNonQuery();
MessageBox.Show(o + "record to be inserted");
con.Close();
}
catch (Exception)
{
MessageBox.Show("error in the code");
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:6)
数据适配器的作用类似于数据库和数据集之间的中介。但是,数据适配器无法存储数据。它只是将数据库中的数据提供给数据集。
例如:
水管用于将水源(井,池塘等)带到目的地。但是,管道不用于储存水。同样,数据适配器(如水管)将数据从数据库发送到数据集。
这应该更清楚地了解数据适配器。
答案 1 :(得分:5)
数据适配器用于将数据读取器中的数据读取到DataTable或DataSet。
由于您没有在此代码中读取数据库中的任何数据,因此数据适配器完全是超级的。
作为旁注,您应该使用参数而不是将值直接放入查询中。您的代码对SQL注入攻击完全开放。
答案 2 :(得分:4)
使用DataAdapter有几个原因:
.Fill()
方法时,它将为您关闭连接;您不必在连接对象上显式调用.Close()
方法。虽然,这仍然是一个很好的做法。在你的情况下,没有必要有一个。但是,如果您确实想要使用一个,那么实现将如下所示:
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
从那里开始,您可以对ds
对象采取进一步的操作,例如通过Interop导出到Excel,填充DataGridView
甚至更新数据库表。
答案 3 :(得分:0)
dataset
或datatable
.Close()