1 ADO.NET 是一种数据访问技术,使得应用程序可以连接到数据存储,并以各种方式操作存储在其中的数据。该技术基于.NET Framework,与.NET Framework类库的其余部分高度集成。ADO.NET API的设计,使得可以从所有面向.NET Framework的语言中使用该API,如Visual Basic、C#、J#、和Visual C++。ADO.NET软件栈包含两个主要部分:提供者和服务。 2 ADO.NET的“提供者”是一些组件,这些组件知道如何与特定的数据存储设施交互(例如,有一个提供者与SQL Server交互,另一个提供者与Oracle数据库交互)。所有的提供者都向外提供一个统一的API接口,ADO.NET软件栈中的其他层在此API之 上建立。 3 ADO.NET还包括基于提供者而建立的一些服务,设计这些服务的目的,是为了方便编写应用程序。其中一个服务是内 存中的缓存(in-memory cache),缓存保存了数据的关系形式,并执行修改跟踪和约束验证等功能;该服务通过ADO.NET DataSet接口提供,包括一些与提供者层进行交互的组件。 4 五大对象分别是: 5 1、Connection(连接数据库) 6 2、Command(执行T-SQL语句) 7 3、DataAdapter(用户填充DataSet,断开模式) 8 4、DataReader(读取数据库,一种只读模式,只向前的) 9 5、DataSet(数据集,好比电脑的内存)介绍
一个经典的图片:
1.首次要准备的(工具)是:a.Microsoft Visual Studio Ultimate 2012;b.Microsoft SQL Server Management Studio ;
2.首先创建一个(SQL Server)数据表,并且填充相应的数据:
1 USE SQL 2 GO 3 --创建数据表中的字段 4 CREATE TABLE SQL_T( 5 [姓名] NVARCHAR(10) NOT NULL, 6 [班级] NVARCHAR(10) NOT NULL, 7 [学号] INT NOT NULL, 8 [分数]DECIMAL(5,2) NOT NULL, 9 [ID] INT IDENTITY(1,1) NOT NULL, --标识列 10 CONSTRAINT PK_SQL_T_1 PRIMARY KEY CLUSTERED([ID]DESC) --添加主键约束,降序排列 11 --对索引进行一定的设置 12 WITH( 13 PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON 14 )ON[PRIMARY] 15 16 )ON[PRIMARY] 17 GO 18 --下面写入数据: 19 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ --设置级别 20 BEGIN TRANSACTION INSERT_SQL_T_1 21 INSERT INTO SQL_T ([姓名] ,[班级] ,[学号] ,[分数] ) --选择插入数据的字段 22 VALUES('李晓峰','计算机',6080,99.56) --写入数据 23 COMMIT TRANSACTION INSERT_SQL_T_1 --提交 24 GO 25 26 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ --设置级别 27 BEGIN TRANSACTION INSERT_SQL_T_2 28 INSERT INTO SQL_T ([姓名] ,[班级] ,[学号] ,[分数] ) --选择插入数据的字段 29 VALUES('李异峰','会计',885,98.23) --写入数据 30 COMMIT TRANSACTION INSERT_SQL_T_2 --提交 31 32 go 33 34 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ --设置级别 35 BEGIN TRANSACTION INSERT_SQL_T_3 36 INSERT INTO SQL_T ([姓名] ,[班级] ,[学号] ,[分数] ) --选择插入数据的字段 37 VALUES('晓峰','英语',5871,87.6) --写入数据 38 COMMIT TRANSACTION INSERT_SQL_T_3 --提交 39 40 go 41 42 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ --设置级别 43 BEGIN TRANSACTION INSERT_SQL_T_4 44 INSERT INTO SQL_T ([姓名] ,[班级] ,[学号] ,[分数] ) --选择插入数据的字段 45 VALUES('李四','电子技术',54,65.51) --写入数据 46 COMMIT TRANSACTION INSERT_SQL_T_4 --提交 47 48 go 49 50 SET TRANSACTION ISOLATION LEVEL REPEATABLE READ --设置级别 51 BEGIN TRANSACTION INSERT_SQL_T_1 52 INSERT INTO SQL_T ([姓名] ,[班级] ,[学号] ,[分数] ) --选择插入数据的字段 53 VALUES('张三','美术',80,256.56) --写入数据 54 COMMIT TRANSACTION INSERT_SQL_T_1 --提交 55 go 56 57 --下面显示写入的数据表 58 SELECT* 59 FROM[SQL_T] 60 GO
3.1.在VS2012中加载上面创建的数据表;
菜单中选择【项目】-选择【添加数据源】-【数据库】-【数据集】-点击新建连接-刷新服务器名后选择-然后选择对应数据表的数据库-最后点击测试连接,如下图:
然后点击下一步,下一步,完成.(以上我们是用windows身份进行连接的,此外还可以使用sql server 身份进行连接。)
然后进入SQL Server对象资源管理器中查看刚刚加载的数据库:
接下来接可以在WindowsForms上进行操作了。
4.1.创建数据库的连接:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; //包含数据库连接对象的命名空间 11 12 namespace WindowsFormsApplication1 13 { 14 public partial class Form1 : Form 15 { 16 public Form1() 17 { 18 InitializeComponent(); 19 } 20 21 private void button1_Click(object sender, EventArgs e) 22 { 23 if (textBox1.Text == "") 24 { MessageBox.Show("请输入要连接的数据库名!"); } 25 else 26 { 27 try 28 { //连接对象其中的字符串中包含了服务器名:可以是本机的ip地址,要连接的数据库,连接的身份,,注意“Data Source=PQC-PC\\SQLEXPRESS;”是2个“\\” 29 SqlConnection sqlconn = new SqlConnection("Data Source=PQC-PC\\SQLEXPRESS;Initial Catalog=" + textBox1.Text.Trim() + ";Integrated Security=True;Connect Timeout=15;
Encrypt=False;TrustServerCertificate=False"); 30 sqlconn.Open(); //打开连接 31 //判断连接的状态: 32 if (sqlconn.State == ConnectionState.Open) 33 { MessageBox.Show("恭喜已经成功连接到数据库了!"); } 34 35 sqlconn.Close(); 36 } 37 catch 38 { { MessageBox.Show("连接失败!"); } } 39 } 40 41 42 } 43 } 44 }
4.2.1.colse()方法关闭数据库连接同上;
4.2.2.比较colse()方法和 Dispose ()都是关闭数据库连接的方法,区别就是: Dispose 不仅关闭一个连接而且还要清理连接所暂用的资源,当用close关闭连接后可以用open方法再次打开,而 Dispose 却不能,非要再次对其连接进行初始化;
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; //***** 11 12 13 namespace WindowsFormsApplication1 14 { 15 public partial class Form2 : Form 16 { 17 public Form2() 18 { 19 InitializeComponent(); 20 } 21 SqlConnection sqlconn; 22 private void button1_Click(object sender, EventArgs e) 23 { 24 if (textBox1.Text == "") 25 { 26 errorProvider1.SetError(textBox1, "这里不能为空!"); //验证提示输入 27 28 } 29 else 30 { 31 try 32 { 33 string sql_conn = "Data Source=PQC-PC\\SQLEXPRESS;Initial Catalog=" + textBox1.Text.Trim() + ";Integrated Security=True;Connect Timeout=15;Encrypt=False;
TrustServerCertificate=False"; 34 sqlconn = new SqlConnection(sql_conn); //建立连接 35 sqlconn.Open(); // 打开连接 36 if (sqlconn.State == ConnectionState.Open) //判断连接的状态 37 { 38 listBox1.Items.Add("数据库连接成功\n"); 39 this.toolStripStatusLabel1.Text = "数据库连接成功"; 40 } 41 } 42 catch (Exception ex) //显示错误信息提示 43 { 44 listBox1.Items.Add(ex.Message ); 45 this.toolStripStatusLabel1.Text = "数据库连接失败!"; 46 } 47 } 48 49 } 50 51 private void Form2_Load(object sender, EventArgs e) 52 { 53 AcceptButton = button1; 54 listBox1.HorizontalScrollbar = true; listBox1.ScrollAlwaysVisible = true; 55 listBox1.SelectionMode = SelectionMode.MultiExtended; 56 57 } 58 59 private void button2_Click(object sender, EventArgs e) 60 { 61 sqlconn.Close(); //Close方法关闭 62 try 63 { 64 sqlconn.Open(); 65 if (sqlconn.State == ConnectionState.Open) 66 { 67 listBox1.Items.Add("恭喜再次连接成功!\n"); this.toolStripStatusLabel1.Text = "ok"; 68 } 69 } 70 catch (Exception ex) 71 { listBox1.Items.Add(ex.Message +"\n"); } 72 73 } 74 75 private void button3_Click(object sender, EventArgs e) 76 { 77 sqlconn.Dispose(); 78 try 79 { 80 sqlconn.Open(); 81 if (sqlconn.State == ConnectionState.Open) 82 { 83 listBox1.Items.Add("恭喜再次连接成功!\n"); this.toolStripStatusLabel1.Text = "ok"; 84 } 85 } 86 catch (Exception ex) 87 { listBox1.Items.Add(ex.Message + "\n"); toolStripStatusLabel1.Text = "有问题!"; } 88 } 89 } 90 }
5.1.使用command对象编辑(增/删/改)数据表:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; 11 12 13 namespace WindowsFormsApplication1 14 { 15 public partial class Form3 : Form 16 { 17 public Form3() 18 { 19 InitializeComponent(); 20 } 21 22 SqlConnection sqlconn; //连接对象 23 SqlCommand sqlcomm; //sql修改对象 24 SqlDataAdapter sda; //适配器 25 26 string str_conn = "Data Source=PQC-PC\\SQLEXPRESS;Initial Catalog=SQL;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"; 27 28 29 private void Form3_Load(object sender, EventArgs e) 30 { 31 sqlconn = new SqlConnection(str_conn ); 32 sqlcomm = new SqlCommand("select* from[SQL_T]",sqlconn ); //查询操作 33 sda = new SqlDataAdapter(sqlcomm ); //实例化适配 34 DataSet ds1 = new DataSet(); 35 sda.Fill(ds1,"cs1" ); //填充ds1数据池 36 dataGridView1.DataSource=ds1.Tables["cs1"]; //将数据池里的【cs1】表显示在datagridview控件上 37 38 39 40 } 41 42 // 43 private void xianshi_datagridview2() //创建一个显示修改后的方法 44 { 45 46 //下面将修改后的数据显示在另一个控件上: 47 sqlconn = new SqlConnection(str_conn ); 48 sqlcomm = new SqlCommand("select* from[SQL_T]", sqlconn); 49 sda = new SqlDataAdapter(sqlcomm ); 50 DataSet ds2 = new DataSet(); 51 sda.Fill(ds2, "cs2"); 52 dataGridView2.DataSource = ds2.Tables["cs2"]; 53 54 } 55 56 private void zengjia_button_Click(object sender, EventArgs e) 57 { 58 if (xingming.Text == "" && banji.Text == "" && xuehao.Text == "" && fenshu.Text == "") //判断添加的信息是否齐全 59 { MessageBox.Show("只有齐全的数据才能添加哦!", "", MessageBoxButtons.OK, MessageBoxIcon.Error); } 60 else 61 { 62 sqlconn.Open(); //打开连接 63 64 sqlcomm.CommandText = "INSERT INTO SQL_T ([姓名] ,[班级] ,[学号] ,[分数] ) VALUES(" 65 + "'" + xingming.Text.Trim() + "'" + "," + "'" + banji.Text.Trim() + "'" + "," + xuehao.Text.Trim() + "," + fenshu.Text.Trim() + ")"; 66 67 //说明CommandType的属性为SQL文本命令 68 sqlcomm.CommandType = CommandType.Text; 69 70 //使用ExecuteNonQuery()前要打开连接 71 int i = Convert.ToInt32(sqlcomm.ExecuteNonQuery()); 72 73 this.toolStripStatusLabel1.Text = "已经成功添加了"+i.ToString()+"行数据。"; 74 75 sqlconn.Close(); //关闭数据连接 76 77 xianshi_datagridview2(); //调用显示修改后的方法 78 79 80 } 81 } 82 83 private void zengjia_button_MouseCaptureChanged(object sender, EventArgs e) 84 { 85 86 } 87 88 private void xiugai_button_Click(object sender, EventArgs e) 89 { 90 sqlconn.Open(); //打开连接 91 sqlcomm.CommandText = "update SQL_T set [姓名]=" + "'" + xingming.Text.Trim() + "'" + "," + "[班级]=" + "'" + banji.Text.Trim() + "'" + "," + "[学号]=" + xuehao.Text.Trim()+","+"[分数]="+fenshu.Text.Trim()+" where [ID]="+id.Text.Trim() ; 92 sqlcomm.CommandType=CommandType.Text; 93 int i = Convert.ToInt32(sqlcomm.ExecuteNonQuery()); 94 95 this.toolStripStatusLabel1.Text = "修改了" + i.ToString() + "记录"; 96 97 sqlconn.Close(); //关闭数据连接 98 99 xianshi_datagridview2(); //调用显示修改后的方法 100 101 } 102 103 private void shanchu_button_Click(object sender, EventArgs e) 104 { 105 sqlconn.Open();//打开连接 106 sqlcomm.CommandText = "DELETE FROM SQL_T WHERE [ID]=" + id.Text.Trim(); 107 sqlcomm.CommandType = CommandType.Text; 108 int i = Convert.ToInt32(sqlcomm.ExecuteNonQuery()); 109 this.toolStripStatusLabel1.Text = "已经成功删除了"+i.ToString()+"句话!"; 110 sqlconn.Close(); 111 xianshi_datagridview2(); 112 } 113 } 114 }
检验1:
2.增加一条数据(姓名=你好,学号=110,班级=没有,分数=3):
3.将刚刚增加的数据修改成(姓名=好的,学号=520,班级=不告诉你,分数=100):
4.删除这条数据:
5.2.在(视图)datagridview控件上修改一条记录:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; 11 12 13 namespace WindowsFormsApplication1 14 { 15 public partial class Form4 : Form 16 { 17 public Form4() 18 { 19 InitializeComponent(); 20 } 21 22 SqlConnection sqlconn = new SqlConnection("Data Source=PQC-PC\\SQLEXPRESS;Initial Catalog=SQL;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"); 23 24 private void Form4_Load(object sender, EventArgs e) 25 { 26 SqlCommand sqlcomm = new SqlCommand("select* from[SQL_T]",sqlconn ); 27 SqlDataAdapter sda = new SqlDataAdapter(sqlcomm ); 28 DataSet ds = new DataSet(); 29 sda.Fill(ds,"cs" ); 30 dataGridView1.DataSource=ds.Tables["cs"]; 31 32 33 } 34 35 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 36 { 37 try 38 { 39 //将控件中对应的信息赋值给对用的textbox 40 id.Text = dataGridView1.SelectedCells[4].Value.ToString(); 41 xingming.Text = dataGridView1.SelectedCells[0].Value.ToString(); 42 banji.Text = dataGridView1.SelectedCells[1].Value.ToString(); 43 xuehao.Text = dataGridView1.SelectedCells[2].Value.ToString(); 44 fenshu.Text = dataGridView1.SelectedCells[3].Value.ToString(); 45 } 46 catch (Exception ex) 47 { this.toolStripStatusLabel1.Text = ex.Message; } 48 } 49 50 private void 确定修改_Click(object sender, EventArgs e) 51 { 52 SqlCommand sqlcomm = new SqlCommand("select* from[SQL_T]", sqlconn); 53 SqlDataAdapter sda = new SqlDataAdapter(sqlcomm); 54 DataSet ds1 = new DataSet(); 55 sda.Fill(ds1,"cs1"); 56 DataTable dt1 = new DataTable(); 57 dt1=ds1.Tables["cs1"]; 58 sda.FillSchema(dt1,SchemaType.Mapped ); 59 DataRow dr = dt1.Rows.Find (id.Text ); //读取主键行 60 //将textbox中对应的信息赋值给datatable中的对应行信息 61 dr["姓名"] = xingming.Text.Trim(); 62 dr["班级"] = banji.Text.Trim(); 63 dr["学号"] = xuehao.Text.Trim(); 64 dr["分数"] = fenshu.Text.Trim(); 65 SqlCommandBuilder sqlcb = new SqlCommandBuilder(sda ); 66 sda.Update(dt1 ); 67 dataGridView1.DataSource=ds1.Tables["cs1"]; 68 toolStripStatusLabel1.Text = "修改成功!"; 69 70 } 71 } 72 }
检验:1.
2.
3.
5.3.在(视图)datagridview控件上修改单元格:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Data.SqlClient; 11 12 13 namespace WindowsFormsApplication1 14 { 15 public partial class Form5 : Form 16 { 17 public Form5() 18 { 19 InitializeComponent(); 20 } 21 22 SqlConnection sqlconn = new SqlConnection("Data Source=PQC-PC\\SQLEXPRESS;Initial Catalog=SQL;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"); 23 24 private void Form5_Load(object sender, EventArgs e) 25 { 26 SqlDataAdapter sda = new SqlDataAdapter("select* from[SQL_T]",sqlconn ); 27 DataSet ds = new DataSet(); 28 sda.Fill(ds,"cs"); 29 dataGridView1.DataSource=ds.Tables["cs"]; 30 31 32 } 33 private DataTable copy_t() //复制一个数据表方法 34 { 35 SqlDataAdapter sda = new SqlDataAdapter("select* from[SQL_T]", sqlconn); 36 DataTable dt = new DataTable(); 37 int i = sda.Fill(dt ); 38 return dt; 39 } 40 private Boolean up_show() //更改的方法,其中更改方法中自动调用 copy_t() //复制一个数据表方法 41 { 42 SqlDataAdapter sda = new SqlDataAdapter("select* from[SQL_T]", sqlconn); 43 DataTable up_dt = copy_t(); 44 up_dt.Rows.Clear(); 45 DataTable show_dt = (DataTable)this.dataGridView1.DataSource; 46 for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) 47 { up_dt.ImportRow(show_dt.Rows[i]); } 48 49 try 50 { 51 sqlconn.Open(); 52 53 sda = new SqlDataAdapter("select* from[SQL_T]", sqlconn ); 54 SqlCommandBuilder sqlcb = new SqlCommandBuilder(sda ); 55 sda.Update(up_dt); 56 } 57 catch (Exception ex) 58 { this.toolStripStatusLabel1.Text = ex.Message; sqlconn.Close(); return false; } 59 up_dt.AcceptChanges(); //提交更改的数据 60 sqlconn.Close(); 61 this.toolStripStatusLabel1.Text = "ok"; 62 return true; 63 } 64 65 private void button1_Click(object sender, EventArgs e) 66 { 67 if (up_show()) //调用更改方法 68 { MessageBox.Show("恭喜,数据已经修改成功!"); } 69 else 70 { MessageBox.Show("操作失败!"); } 71 } 72 } 73 }
检验:
1. 将姓名为:李异峰,班级=C#.NET;姓名为:李晓峰,学号=880,班级=asp.net;
--在Microsoft SQL Server Management Studio中查询: