ADO.NET 是微软公司在.NET平台下提出的新的数据访问模型。
在ADO.NET中,可以使用多种 .NETFramework 数据提供程序来访问数据源。
(1) SQL Server.NET Framework 数据提供程序:使用 System.Data.SqlClient 命名空间,用于访问 SQLServer 数据
库等。
(2) OLE DB.NET Framework 数据提供程序:使用 System.Data.OleDb 命名空间,用于访问OLE DB公开的数据源,如
Access数据库等。
(3) Oracle.NET Framework 数据提供程序:使用 System.out.OracleClient 命名空间,用于访问Oracle数据库。
(4) ODBC.NET Framework 数据提供程序: 使用 System.Data.Odbc 命名空间,用于访问ODBC公开的数据源,如Visual
FoxPro 数据库等。
经本人总结一共大致有3大类访问数据库的方式。
一、直接利用连接字符串和command命令来连接数据库(最简单但是最复杂)
如下例子:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StudentInfo_Test
{
public partial class Form1 : Form
{
SqlDataAdapter adapter;
BindingSource bindingSource1 = new BindingSource();
DataTable table1 = new DataTable();
String connString = Properties.Settings.Default.StudentInfoConnectionString;
public Form1()
{
InitializeComponent();
}
//打开
private void button1_Click(object sender, EventArgs e)
{
//第一种方法,如果没有adapter和bindingSource1
SqlConnection conn = new SqlConnection(connString);
String sql = "select * from StudentInfo";
adapter = new SqlDataAdapter(sql, conn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Fill(table1);
bindingSource1.DataSource = table1;
dataGridView1.DataSource = bindingSource1;
}
//保存修改
private void button2_Click(object sender, EventArgs e)
{
if (this.Validate())
{
this.bindingSource1.EndEdit();
this.adapter.Update(table1);
MessageBox.Show("修改成功!");
}
else
{
MessageBox.Show("修改失败!");
}
}
//查询
private void button3_Click(object sender, EventArgs e)
{
String id = textBox1.Text.Trim();
SqlConnection conn1 = new SqlConnection(connString);
conn1.Open();
String sql1 = "select datediff(year, birthday, GETDATE()) AS age from studentInfo where (studentNo = '"+ id +"')";
SqlCommand cmd = new SqlCommand(sql1, conn1);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while(reader.Read())
{
textBox2.Text = reader[0].ToString();
}
}
else
{
MessageBox.Show("不存在此学号!");
}
}
}
}
二、利用强类型数据集访问数据库,既可以全不手写代码,又可以在界面中搞定!
1.先说直接用代码实现数据绑定的方法。
先往你的窗体上拖放一个