C#使用Command将dataGrideView表格内数据与数据库交互
本文主要介绍通过Command类使用SQL插入指令insert与查询指令select将dataGrideView表格内添加至数据库,与从数据库读出数据存放在dataGrideView表格中。
C#制作的界面如下:(制作过程不再详述)
- 点击"创建数据"按钮,将姓名、性别、年龄文本框中的数据写入表格;
- 点击"存入数据库"按钮,将表格中数据存入数据库,存入成功后将表格内容清除;
- 点击"读取数据"按钮,将读取数据库中的内容并添加到表格中。
在编程之前向使用SQL Server创建数据库:mydb001,并在数据库中创建数据表:mytable001;
在数据表mytable001中添加列信息:ID(主键、自动赋值)、姓名(nvarchar(20))、性别(nvarchar(5))、年龄(int)。
如图:
C#代码如下:
using System;
using System.Windows.Forms;
using System.Data.SqlClient; namespace 使用Command将表格中数据写入数据库
{
public partial class Form1 : Form
{
private SqlConnection myConnection = new SqlConnection();
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
//定义字符串
string connectionStr = "Server=localhost;integrated security=SSPI;Initial Catalog=mydb001";
//创建连接对象
myConnection = new SqlConnection(connectionStr);
//测试是否连接成功
try
{
myConnection.Open();//打开数据库
}
catch
{
MessageBox.Show("数据库连接错误","错误提示");
}
finally
{
myConnection.Close();//关闭数据库
}
listGender.Items.Add("男");
listGender.Items.Add("女");
listGender.SelectedIndex = ;
textName.Text = "";
toolStripStatusLabel1.Text = "";
} private void btnCreatData_Click(object sender, EventArgs e)
{
if (textName.Text.Trim() == "")
{
MessageBox.Show("请输入姓名!","错误提示");
return;
}
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[].Value = textName.Text.Trim();
dataGridView1.Rows[index].Cells[].Value = listGender.SelectedItem.ToString();
dataGridView1.Rows[index].Cells[].Value = numAge.Value;
toolStripStatusLabel1.Text = "向表格添加数据完成!";
} private void btnSaveData_Click(object sender, EventArgs e)
{
bool result = true;
try
{
myConnection.Open();//打开数据库
for (int i = ; i < dataGridView1.RowCount; i++)
{
string commandSQLStr = "";//命令字符串
string commandSQLStr1 = "insert into mytable001(";//命令字符串
string commandSQLStr2 = ")values(";//命令字符串
string commandSQLStr3 = ")";//命令字符串
for (int j = ; j < dataGridView1.ColumnCount; j++)
{
if (j == )
{
commandSQLStr1 = commandSQLStr1 + dataGridView1.Columns[j].HeaderText.ToString();
if (dataGridView1.Rows[i].Cells[j].Value.GetType() == typeof(string))
{
commandSQLStr2 = commandSQLStr2 +"\'"+ dataGridView1.Rows[i].Cells[j].Value.ToString() + "\'";
}
else
{
commandSQLStr2 = commandSQLStr2 + dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
else
{
commandSQLStr1 = commandSQLStr1 + "," + dataGridView1.Columns[j].HeaderText.ToString();
if (dataGridView1.Rows[i].Cells[j].Value.GetType() == typeof(string))
{
commandSQLStr2 = commandSQLStr2 + "," + "\'" + dataGridView1.Rows[i].Cells[j].Value.ToString() + "\'";
}
else
{
commandSQLStr2 = commandSQLStr2 + "," + dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
}
commandSQLStr = commandSQLStr1 + commandSQLStr2 + commandSQLStr3;
SqlCommand myCommand = new SqlCommand(commandSQLStr, myConnection);//创建Command对象
myCommand.CommandTimeout = ;//设置超时时间为5秒
myCommand.ExecuteNonQuery();
}
}
catch
{
result = false;
}
finally
{
myConnection.Close();//关闭数据库
} if (result)
{
dataGridView1.Rows.Clear();
toolStripStatusLabel1.Text = "写入数据库成功!";
}
else
{
toolStripStatusLabel1.Text = "写入数据库失败!";
}
} private void btnReadData_Click(object sender, EventArgs e)
{
try
{
myConnection.Open();
string commandSQLStr = "select * from mytable001";//命令字符串
SqlCommand myCommand = new SqlCommand(commandSQLStr, myConnection);//创建Command对象
myCommand.CommandTimeout = ;//设置超时时间为5秒
SqlDataReader myDataReader = myCommand.ExecuteReader();
while (myDataReader.Read())
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[].Value = myDataReader.GetValue();
dataGridView1.Rows[index].Cells[].Value = myDataReader.GetValue();
dataGridView1.Rows[index].Cells[].Value = myDataReader.GetValue();
}
myDataReader.Close();
toolStripStatusLabel1.Text = "从数据库读取数据完成!";
}
catch
{
toolStripStatusLabel1.Text = "从数据库读取数据失败!";
}
finally
{
myConnection.Close();
}
}
}
}
C#使用Command将dataGrideView表格内数据与数据库交互的更多相关文章
- 如何将Excl内数据导入数据库?
最近有个Excl表格内的数据需要导入SQL Server数据库内,使用SQL Server Management Studio客户端图形界面操作了一番,步骤还挺多,感觉有必要分享给大家一下,顺便自己也 ...
- BootStrap table动态增删改表格内数据
1:添加一个[操作]列 { title: "操作", align: 'center', valign: 'middle', width: 160, // 定义列的宽度,单位为像 ...
- js遍历获取表格内数据方法
1.一般的表格结构如下 <table> <tr> <td>id</td> <td>name</td> </tr> & ...
- 从Excel表格导入数据到数据库
数据库:SQL 1.小数据直接粘贴 2.用导入向导 3.用SSIS包 4.用SQL语句 现在详细说一下第4种方法,以.xlsx文件为例 .xlsx文件需要用provider“Microsoft.ACE ...
- Android系统编程入门系列之应用内数据保存数据库
上篇文章已经介绍了如何使用SharedPreferences存储键值对形式的轻量级数据,对于那些相同结构的多组数据,类似于存储Java中定义的类的多个对象属性值,如果按照键值对的形式一条条读写,需要分 ...
- Python+Selenium+Mysql(动态获取数据,数据库交互)
一.创建数据库连接 #!coding:utf-8 import pymysql ''' Python3之后不再支持MySQLdb的方式进行访问mysql数据库: 可以采用pymysql的方式 连接方式 ...
- 使用openpyxl模块将Excel中的数据导入数据库
这里将不介绍openpyxl模块的详细操作. 主要就是记录一个使用openpyxl模块将Excel表格的数据导入数据库中的实例. from openpyxl import load_workbook ...
- 怎么把excel表格内的数据导入数据库?
第一种方法: 思路:想要把excel表格内的数据直接导入数据库不是那么容易,可以把excel表格另存为.csv格式的文档(特点:内容以逗号分割):然后通过一系列的文档操作函数处理成为一个二维数组,然后 ...
- Linqpad使用(调试Linq、结合linq调试业务场景、表格内编辑数据)
linqpad是一款linq语句调试工具,功能如下: 1.直接执行linq语句并查看生成的原生sql语句 2.可结合linq+C#代码进行业务场景调试 3.表格内直接新增.修改.删除数据 4.直接 ...
随机推荐
- centos7 使用 maven
http://www.cnblogs.com/jackluo/archive/2013/02/06/2901816.html
- Nodejs课堂笔记-第四课 Dynamodb为何物
本文由Vikings(http://www.cnblogs.com/vikings-blog/) 原创,转载请标明.谢谢! 我喜欢带着目标来学习新知识.因此学习nodejs过程中,不喜欢只看枯燥的语法 ...
- SQL的优化1
1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引. 2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索 ...
- Bootstrap学习1--响应式导航栏
备注:最新Bootstrap手册:http://www.jqhtml.com/bootstraps-syntaxhigh/index.html <nav class="navbar n ...
- LeetCode:移动零【283】
LeetCode:移动零[283] 题目描述 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例: 输入: [0,1,0,3,12] 输出: [1,3 ...
- SpringBoot学习笔记(2):引入Spring Security
SpringBoot学习笔记(2):用Spring Security来保护你的应用 快速开始 本指南将引导您完成使用受Spring Security保护的资源创建简单Web应用程序的过程. 参考资料: ...
- QCon2016 上海会议汇总(2) - 团队管理
QCon 2016上海日程:http://2016.qconshanghai.com/schedule <当你的团队还支撑不起梦想时> - 链尚网技术合伙人 杨荣伟 Figo讲述了如何训练 ...
- 培训笔记——Linux目录说明
一般我们的电脑里都只有一块硬盘,但是这块硬盘怎么使用呢? 我们的头脑里大体有个分区的概念,为什么要分区呢? 不是很清楚,不过有句话说 不要把鸡蛋放在同一个篮子里,可能有这种考虑吧. 好,最起码知道分区 ...
- GUI菜单——菜单条、菜单、子条目之间关系
菜单:注意区分三个概念:菜单条.菜单.菜单项 将菜单条添加到窗体,菜单条下面包括菜单,菜单下面可以使菜单或者菜单项 菜单项是最后一个.菜单后面有三角标示. 菜单条[文件] 子菜单--子条目 子条目 示 ...
- linux操作系统使用中的一些总结
VIM常用命令 gg //到第一行 (N)G //到第n行(N为整数) G //到最后一行 0 //到行头 $ //到行尾 (N)dd //删除N行,并将内容保存到粘贴板 p ...