如何在前端界面操作数据表(读书笔记3)

一.思维导图

 

二.知识点描述

通过分析,我将对数据表的操作分为:A.检验是否与数据表的数据相同。B.通过控件输入输出更新数据表。

以下我用两个控件对数据表进行操作。

1.通过TextBox操作数据表

(1)通过连接数据库,将TextBox中的数据与数据库的数据匹配。

以下相关知识点

1.Sqlconnection类

 属性:

ConnectionString:获取或设置用于打开 SQL Server 数据库的字符串。

方法:

0pen():使用 ConnectionString 所指定的属性设置打开数据库连接。

Close():关闭与数据库的连接。 此方法是关闭任何已打开连接的首选方法。

CreateCommand():创建并返回一个与 SqlConnection 关联的 SqlCommand 对象。

2.SqlCommand类

属性 Connection 获取或设置SqlCommand的实例使用的SqlConnection。
  CommandText 获取或设置要对数据源执行的Transact—SQL语句或存储过程。
  CommandType 获取或设置一个值,该值指示如何解释CommandText属性。
  Parameters 参数化查询
方法 ExecuteNonQuery() 返回值类型为int型。多用于执行增加,删除,修改数据。返回受影响的行数。
  ExecuteReader() 返回类型为SqlDataReader。此方法用于用户进行的查询操作。使用SqlDataReader对象的Read();方法进行逐行读取。
  ExecuteScalar() 返回值类型多为int类型。它返回的多为执行select查询。得到的返回结果为一个值的情况,比如使用count函数求表中记录个数或者使用sum函数求和等。

 

 

 

 

2.通过DataGridView操作数据表

1.SqlDataAdapter类

属性:

Insertcommand:在 Sqlcommand 过程中使用 Update(DataTable),以在数据库中插入对应于 DataTable 中的新行的记录

Selectcommand:在 Sqlcommand 过程中使用的 Fill(DataTable),用来从数据库中为 DataTable  中的位置选择记录。

Updatecomm:在 Sqlcommand 过程中使用的 Update(DataTable),用于在数据库中更新对应于DataTable  中已修改行的记录。

2.SqlDataReader类

属性:

HasRows:获取一个值,该值指示 SqlDataReader 是否包含一行还是多行。如果 SqlDataReader 包含一行或多行,则为 true;否则为 false

方法:

Close():关闭SqlDataReader对象。

Read():让 SqlDataReader前进到下一条记录。如果存在更多行,则为 true;否则为 false

3.DataTable类

表示内存中数据的一个表

属性:

Columns:获取属于该表的列的集合。一个DataColumnCollection,包含该表的DataColumn 对象的集合。 如果 DataColumn 对象不存在,将返回空集合。

HasErrors:获取一个值,该值指示该表所属的 DataSet 的任何表的任何行中是否有错误。如果有错误,则为 true;否则为 false

Rows:获取属于该表的行的集合。包含 DataColumnCollection 对象的 DataRow;否则为 null 值(如果不存在任何 DataRow 对象)。

方法:

Clear:清除所有数据的DataTable。

Clone:克隆 DataTable的结构,包括所有DataTable架构和约束。新的 DataTable,与当前 DataTable 具有相同架构。

 

三.效果截图和示例代码

 示例1.检验TextBox中的数据是否与数据库中的数据匹配。

 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.Windows.Forms;
 9 
10 using System.Data.SqlClient; 
11 
12 namespace LOGIN
13 {
14     public partial class Form1 : Form
15     {
16         public Form1()
17         {
18             InitializeComponent();
19         }
20 
21         private void Form1_Load(object sender, EventArgs e)
22         {
23             label1.BackColor = Color.Transparent;
24             label2.BackColor = Color.Transparent;
25             label3.BackColor = Color.Transparent;
26         }
27  private void login_Click(object sender, EventArgs e)
28         {
29             SqlConnection sqlConnection = new SqlConnection();                                          
30             sqlConnection.ConnectionString =
31                 "Server=(local);Database=MyHospital;Integrated Security=sspi";                         
32             SqlCommand sqlCommand = sqlConnection.CreateCommand();                                      
33             sqlCommand.CommandText =
34                 "SELECT COUNT(1) FROM Manager WHERE UserID=@UserID AND Password=HASHBYTES('MD5',@Password);";   
35             sqlCommand.Parameters.AddWithValue("@UserID", this.UserID.Text.Trim());             
36             sqlCommand.Parameters["@UserID"].SqlDbType = SqlDbType.Char;
37             sqlCommand.Parameters.AddWithValue("@Password", this.Password.Text.Trim());             
38             sqlCommand.Parameters["@Password"].SqlDbType = SqlDbType.Char;                         
39                                                                                                         
40             sqlConnection.Open();                                                                      
41             int rowCount = (int)sqlCommand.ExecuteScalar();                                             
42             sqlConnection.Close();                                                                      
43             if (rowCount == 1)                                                                          
44             {
45                 MessageBox.Show("登录成功。");
46                 this.Hide();
47                 Main Main = new Main();
48                 Main.Show();
49                 ordersHelper.UserName = UserID.Text;
50             }
51             else                                                                              
52             {
53                 MessageBox.Show("用户号/密码有误,请重新输入!");                              
54                 this.Password.Focus();                                                
55                 this.Password.SelectAll();                                       
56             }
57         }
58     }
59 }

实例二.通过TextBox向数据表导入数据。

 1  private void OrdersOK_Click(object sender, EventArgs e)
 2         {
 3             if (this.Order.Text.Trim() == "")
 4             {
 5                 MessageBox.Show("订单不能为空!");
 6                 this.Order.Focus();
 7                 return;
 8             }
 9             if (this.comb_Supplyname.ValueMember == "")
10             {
11                 MessageBox.Show("供应商不能为空!");
12                 this.Order.Focus();
13                 return;
14             }
15             SqlConnection sqlConnection = new SqlConnection();                                              
16             sqlConnection.ConnectionString =
17             ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;                        
18             SqlCommand sqlCommand = new SqlCommand();                                                       
19             sqlCommand.Connection = sqlConnection;
20             sqlCommand.CommandText =
21                 "INSERT orders (SupplyID,OrderKinds,OrderDate,GetDate,ProducePla) VALUES(@SupplyID,@OrderKinds,@OrderDate,@GetDate,@ProducePla);";                 
22             sqlCommand.Parameters.AddWithValue("@SupplyID",comb_Supplyname.SelectedValue);
23             sqlCommand.Parameters.AddWithValue("@OrderKinds", this.Order.Text.Trim());
24             sqlCommand.Parameters.AddWithValue("@OrderDate", this.dateTimePicker1.Value);
25             sqlCommand.Parameters.AddWithValue("@GetDate", this.dateTimePicker2.Value);
26             sqlCommand.Parameters.AddWithValue("@ProducePla", this.Address.Text.Trim());
27             sqlConnection.Open();                                                                    
28             int rowAffected = sqlCommand.ExecuteNonQuery();                                  
29             sqlConnection.Close();                                                                     
30             if (rowAffected == 1)                                                                     
31             {
32                 MessageBox.Show("添加成功。");
33                 ordersHelper.order = Order.Text.Trim();
34                 if (dateTimePicker2.Value == DateTime.Now)
35                 {
36                     ordersHelper.state = "入库";
37                 }
38                 else {
39                     ordersHelper.state = "未入库";
40                 }
41             }
42             else                                                                                       
43             {
44                 MessageBox.Show("添加失败!");                                                          
45             }
46          
47         }

实例三.通过DataGridView输入输出更新控件

1. 1 private void update_Click(object sender 2 {

 3             SqlConnection sqlConnection = new SqlConnection();                                           
 4             sqlConnection.ConnectionString =
 5                 ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;                             
 6             SqlCommand updateCommand = new SqlCommand();                                                       //声明并实例化SQL命令;
 7             updateCommand.Connection = sqlConnection;                                                         
 8             updateCommand.CommandText =                                                                        //指定SQL命令的命令文本;
 9                 "UPDATE orders"
10                 + " SET SupplyID=@SupplyID,OrderDate=@OrderDate,GetDate=@GetDate,ProducePla=@ProducePla,IndPrice=@IndPrice,Num=@Num,TolPrice=@TolPrice,Guige=@Guige,state=@state"
11                 + " WHERE OrderID=@OrderID;";
12             updateCommand.Parameters.Add("@OrderID", SqlDbType.Char, 10, "OrderID");
13             updateCommand.Parameters.Add("@SupplyID", SqlDbType.Char, 10, "SupplyID");                               //向SQL命令的参数集合添加参数的名称、SQL Server数据类型、长度(仅用于定长类型)、所绑定的数据表中的列名;
14             updateCommand.Parameters.Add("@OrderDate", SqlDbType.DateTime, 0, "OrderDate");
15             updateCommand.Parameters.Add("@GetDate", SqlDbType.DateTime, 0, "GetDate");
16             updateCommand.Parameters.Add("@ProducePla", SqlDbType.VarChar, 0, "ProducePla");
17             updateCommand.Parameters.Add("@IndPrice", SqlDbType.Char, 0, "IndPrice");
18             updateCommand.Parameters.Add("@Num", SqlDbType.Int, 0, "Num");
19             updateCommand.Parameters.Add("@TolPrice", SqlDbType.Int, 10, "TolPrice");
20             updateCommand.Parameters.Add("@Guige", SqlDbType.VarChar, 10, "Guige");                               //向SQL命令的参数集合添加参数的名称、SQL Server数据类型、长度(仅用于定长类型)、所绑定的数据表中的列名;
21             updateCommand.Parameters.Add("@state", SqlDbType.Int, 0, "state");
22             SqlCommand deleteCommand = new SqlCommand();                                                    //声明并实例化SQL命令;该命令用于删除;
23             deleteCommand.Connection = sqlConnection;                                                       //将SQL命令的连接属性指向SQL连接;
24             deleteCommand.CommandText =                                                                     //指定SQL命令的命令文本;
25                 "DELETE orders"
26                 + " WHERE OrderID=@OrderID;";
27             deleteCommand.Parameters.Add("@OrderID", SqlDbType.Char, 10, "OrderID");
28             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                           //声明并实例化SQL数据适配器;
30             sqlDataAdapter.UpdateCommand = updateCommand;                                                   //将SQL数据适配器的属性UpdateCommand指向用于更新记录的SQL命令;
31             sqlDataAdapter.DeleteCommand = deleteCommand;                                                   //将SQL数据适配器的属性DeleteCommand指向用于删除记录的SQL命令;
32             DataTable studentTable1 = (DataTable)this.dgv_orders.DataSource;                                 //声明数据表,并指向数据网格视图的数据源;数据源默认类型为object,还需强制转换类型;
33             sqlConnection.Open();                                                                           //打开SQL连接;
34             int rowAffected = sqlDataAdapter.Update(studentTable1);                                         //SQL数据适配器根据数据表提交所有更新,并返回受影响行数;
35             sqlConnection.Close();                                                                          //关闭SQL连接;
36             MessageBox.Show("更新" + rowAffected.ToString() + "行。"); 

2.实现查找功能

 1 private void ReplenishmentToview_Click(object sender, EventArgs e)
 2         {
 3 
 4             SqlConnection sqlConnection = new SqlConnection();                                              
 5             sqlConnection.ConnectionString =
 6                 "Server=(local);Database=MyHospital;Integrated Security=sspi";                             
 7             SqlCommand sqlCommand = new SqlCommand();                                                      
 8             sqlCommand.Connection = sqlConnection;
 9             if (this.comboBox1.SelectedIndex == 0 && this.search.Text != "")
10             {
11                 sqlCommand.CommandText = "SELECT MedicineID,YKNo,DrugName,Guige,DW,MedicineSum,IndPrice,MinNum FROM medicineData where MedicineID=@MedicineID;";                                          
12             sqlCommand.Parameters.AddWithValue("@MedicineID", this.search.Text.Trim());
13             }
14             else if (this.comboBox1.SelectedIndex == 1 && this.search.Text != "")
15             {
16                 sqlCommand.CommandText = "SELECT MedicineID,YKNo,DrugName,Guige,DW,MedicineSum,IndPrice,MinNum FROM medicineData where DrugName=@DrugName;";                                      
17                 sqlCommand.Parameters.AddWithValue("@DrugName", this.search.Text.Trim());
18             }
19             else if ((this.comboBox1.SelectedIndex == 0 || this.comboBox1.SelectedIndex == 1) && this.search.Text == "")
20             {
21                 sqlCommand.CommandText = "SELECT MedicineID,YKNo,DrugName,Guige,DW,MedicineSum,IndPrice,MinNum FROM medicineData ;";                                        
22             }
23            
24             SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();                                           
25             sqlDataAdapter.SelectCommand = sqlCommand;                                                      
26             DataTable medicalTable = new DataTable();                                                 
27             sqlConnection.Open();                                                                         
28             sqlDataAdapter.Fill(medicalTable);                                                             
29             sqlConnection.Close();                                                                          
30             this.dgvMedical.DataSource = medicalTable;
31             dgvMedical.Columns[0].ReadOnly = true;
32             dgvMedical.Columns[1].ReadOnly = true;
33         }  
原文地址:https://www.cnblogs.com/lidie-/p/9840460.html