C#使用Command将dataGrideView表格内数据与数据库交互

    本文主要介绍通过Command类使用SQL插入指令insert与查询指令select将dataGrideView表格内添加至数据库,与从数据库读出数据存放在dataGrideView表格中。

    C#制作的界面如下:(制作过程不再详述)

  • 点击"创建数据"按钮,将姓名、性别、年龄文本框中的数据写入表格;
  • 点击"存入数据库"按钮,将表格中数据存入数据库,存入成功后将表格内容清除;
  • 点击"读取数据"按钮,将读取数据库中的内容并添加到表格中。

在编程之前向使用SQL Server创建数据库:mydb001,并在数据库中创建数据表:mytable001;

在数据表mytable001中添加列信息:ID(主键、自动赋值)、姓名(nvarchar(20))、性别(nvarchar(5))、年龄(int)。

如图:

 

C#代码如下:

  1 using System;
  2 using System.Windows.Forms;
  3 using System.Data.SqlClient;
  4 
  5 namespace 使用Command将表格中数据写入数据库
  6 {
  7     public partial class Form1 : Form
  8     {
  9         private SqlConnection myConnection = new SqlConnection();
 10         public Form1()
 11         {
 12             InitializeComponent();
 13         }
 14 
 15         private void Form1_Load(object sender, EventArgs e)
 16         {
 17             //定义字符串
 18             string connectionStr = "Server=localhost;integrated security=SSPI;Initial Catalog=mydb001";
 19             //创建连接对象
 20             myConnection = new SqlConnection(connectionStr);
 21             //测试是否连接成功
 22             try
 23             {
 24                 myConnection.Open();//打开数据库
 25             }
 26             catch
 27             {
 28                 MessageBox.Show("数据库连接错误","错误提示");
 29             }
 30             finally
 31             {
 32                 myConnection.Close();//关闭数据库
 33             }
 34             listGender.Items.Add("");
 35             listGender.Items.Add("");
 36             listGender.SelectedIndex = 0;
 37             textName.Text = "";
 38             toolStripStatusLabel1.Text = "";
 39         }
 40 
 41         private void btnCreatData_Click(object sender, EventArgs e)
 42         {
 43             if (textName.Text.Trim() == "")
 44             {
 45                 MessageBox.Show("请输入姓名!","错误提示");
 46                 return;
 47             }
 48             int index = dataGridView1.Rows.Add();
 49             dataGridView1.Rows[index].Cells[0].Value = textName.Text.Trim();
 50             dataGridView1.Rows[index].Cells[1].Value = listGender.SelectedItem.ToString();
 51             dataGridView1.Rows[index].Cells[2].Value = numAge.Value;
 52             toolStripStatusLabel1.Text = "向表格添加数据完成!";
 53         }
 54 
 55         private void btnSaveData_Click(object sender, EventArgs e)
 56         {
 57             bool result = true;
 58             try
 59             {
 60                 myConnection.Open();//打开数据库
 61                 for (int i = 0; i < dataGridView1.RowCount; i++)
 62                 {
 63                     string commandSQLStr = "";//命令字符串
 64                     string commandSQLStr1 = "insert into mytable001(";//命令字符串
 65                     string commandSQLStr2 = ")values(";//命令字符串
 66                     string commandSQLStr3 = ")";//命令字符串
 67                     for (int j = 0; j < dataGridView1.ColumnCount; j++)
 68                     {
 69                         if (j == 0)
 70                         {
 71                             commandSQLStr1 = commandSQLStr1 + dataGridView1.Columns[j].HeaderText.ToString();
 72                             if (dataGridView1.Rows[i].Cells[j].Value.GetType() == typeof(string))
 73                             {
 74                                 commandSQLStr2 = commandSQLStr2 +"\'"+ dataGridView1.Rows[i].Cells[j].Value.ToString() + "\'";
 75                             }
 76                             else
 77                             {
 78                                 commandSQLStr2 = commandSQLStr2 + dataGridView1.Rows[i].Cells[j].Value.ToString();
 79                             }
 80                         }
 81                         else
 82                         {
 83                             commandSQLStr1 = commandSQLStr1 + "," + dataGridView1.Columns[j].HeaderText.ToString();
 84                             if (dataGridView1.Rows[i].Cells[j].Value.GetType() == typeof(string))
 85                             {
 86                                 commandSQLStr2 = commandSQLStr2 + "," + "\'" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\'";
 87                             }
 88                             else
 89                             {
 90                                 commandSQLStr2 = commandSQLStr2 + "," + dataGridView1.Rows[i].Cells[j].Value.ToString();
 91                             }
 92                         }
 93                     }
 94                     commandSQLStr = commandSQLStr1 + commandSQLStr2 + commandSQLStr3;
 95                     SqlCommand myCommand = new SqlCommand(commandSQLStr, myConnection);//创建Command对象
 96                     myCommand.CommandTimeout = 5;//设置超时时间为5秒
 97                     myCommand.ExecuteNonQuery();
 98                 }
 99             }
100             catch
101             {
102                 result = false;
103             }
104             finally
105             {
106                 myConnection.Close();//关闭数据库
107             }
108 
109             if (result)
110             {
111                 dataGridView1.Rows.Clear();
112                 toolStripStatusLabel1.Text = "写入数据库成功!";
113             }
114             else
115             {
116                 toolStripStatusLabel1.Text = "写入数据库失败!";
117             }
118         }
119 
120         private void btnReadData_Click(object sender, EventArgs e)
121         {
122             try
123             {
124                 myConnection.Open();
125                 string commandSQLStr = "select * from mytable001";//命令字符串
126                 SqlCommand myCommand = new SqlCommand(commandSQLStr, myConnection);//创建Command对象
127                 myCommand.CommandTimeout = 5;//设置超时时间为5秒
128                 SqlDataReader myDataReader = myCommand.ExecuteReader();
129                 while (myDataReader.Read())
130                 {
131                     int index = dataGridView1.Rows.Add();
132                     dataGridView1.Rows[index].Cells[0].Value = myDataReader.GetValue(1);
133                     dataGridView1.Rows[index].Cells[1].Value = myDataReader.GetValue(2);
134                     dataGridView1.Rows[index].Cells[2].Value = myDataReader.GetValue(3);
135                 }
136                 myDataReader.Close();
137                 toolStripStatusLabel1.Text = "从数据库读取数据完成!";
138             }
139             catch
140             {
141                 toolStripStatusLabel1.Text = "从数据库读取数据失败!";
142             }
143             finally
144             {
145                 myConnection.Close();
146             }
147         }
148     }
149 }

 

转载于:https://www.cnblogs.com/nicewe/p/8580892.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 基类说明 1.1 基类结构图 1.2 基类说明 1.2.1 BaseEditClass BaseEditClass是所有单表编辑功能的基类。BaseEditClass从NSGForm继承,以处理统一的界面和字体风格。 BaseEditClass抽象出了编辑类功能通用的方法并定义为基类方法,以便子类继承,并增加自己的代码。  自定义属性 名称 说明 DataTable 功能所编辑的数据表 DataState 功能所处的状态:浏览(dsBrowse)、新增(dsInsert)、编辑(dsEdit) BatchSave 是否批量提交数据表,默认为False DeleteWarn 在删除记录时是否提示,默认为True  自定义方法 名称 说明 FormInit 在FormLoad时被调用,具体功能中可重载该方法添加自定义的初始化代码 PostData 具体功能中需要重载该方法,并调用具体的TableAdapter.Update(row),以保存数据数据库。 RefreshData 统一的刷新数据表过程,具体功能中需要重载该方法,并调用具体的TableAdapter.Fill(DataTable),以查询数据 DataValid 统一的数据验证方法,在保存数据前被调用。具体功能中可重载该方法添加自定义的数据校验代码 NewRecord 在新增数据时被调用,在具体过程中可重载该方法添加自定义的新增记录默认值 SaveData 保存数据的方法,具体功能中调用该过程保存数据 DeleteData 删除数据的方法,具体功能中调用该过程删除数据 CancelData 取消数据修改的方法,具体功能中调用该过程取消数据修改 1.2.2 BaseGridEdit BaseGridEdit是所有直接使用DataGridView进行编辑的功能的基类。BaseGridEdit从BaseEditClass继承。 自定义属性 名称 说明 Grid 编辑所用的DataGridView 自定义方法 名称 说明 RecordValid 统一的数据验证方法,在单条保存数据前被调用。具体功能中可重载该方法添加自定义的数据校验代码 1.2.3 BaseGridEditForm BaseGridEditForm是所有直接使用DataGridView进行编辑的功能的模板。所有直接使用DataGridView进行编辑的功能都需要从该模板拷贝后进行修改。 2. 模板使用方法 2.1 BaseGridEditForm 使用BaseGridEditForm需要按以下四步操作就可以得到需要的功能。 一、 先从BaseGridEditForm拷贝文件到工程后修改类名、命名空间 二、 在项目的数据集中增加TableAdapter,以查询需要维护的指定的数据表 三、 将DataGridView绑定到新增的数据表 四、 修改以下基类方法 名称 说明 构造方法 增加”DataTable属性=新增数据表”的代码 FormInit 增加需要的Form初始化代码,如RefreshData以获得数据 PostData 增加一行代码:新增的TableAdapter.Update(row) RefreshData 增加使用新增TableAdapter.Fill(DataTable)的代码,以获得查询数据。注意:代码需要写在IsRefreshData = true;和 IsRefreshData = false;语句的中间 RecordValid 增加自定义的数据校验语句。 NewRecord 增加自定义的新增数据默认值代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值