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.直接 ...
随机推荐
- 使用 Python 为 KVM 编写脚本,第 1 部分: libvirt
虚拟化是目前市场上大多数服务器操作系统的标准设备.在 Linux® 的世界里,服务器虚拟化有两个主要选择:基于 Kernel 的虚拟机 (KVM) 和 Xen.KVM 是 Red Hat 和其他公司采 ...
- vuex源码 安装依赖问题
今天下载vuex源码时 安装依赖出现以下问题 > chromedriver@2.32.3 install /Users/bao/Desktop/vue-store/vuex/node_modul ...
- Data Structure Array: Given an array arr[], find the maximum j – i such that arr[j] > arr[i]
http://www.geeksforgeeks.org/given-an-array-arr-find-the-maximum-j-i-such-that-arrj-arri/ #include & ...
- js 实现滑块效果
var dd = $(".drag_bott").removeAttr('id').last().attr('id','drag_bott'); var drag = docume ...
- <linux是怎么跑的?>傻瓜视角看linux引导启动过程
每天开机关机,除了“等”之外,你得了解你的操作系统开机的时候真正做了什么? 一. 书上都是这么讲的 CPU自身初始化:硬件初始工作,以PC/IP寄存器跳转到BIOS首地址为结束标志. ->加电自 ...
- HTML入门学习笔记
1.html文件的基本架构 <HTML> <HEAD> <TITLE> 网页的标题 </TITLE> </HEAD> <BODY> ...
- 《机器学习实战》学习笔记第九章 —— 决策树之CART算法
相关博文: <机器学习实战>学习笔记第三章 —— 决策树 主要内容: 一.CART算法简介 二.分类树 三.回归树 四.构建回归树 五.回归树的剪枝 六.模型树 七.树回归与标准回归的比较 ...
- meta 标签代码解决IE兼容问题,IE6,IE7,IE8,IE9,IE10(包括360的兼容模式)
最近做了一个项目,客户反映,在360下布局错位,远程调试了一下,发现客户使用的是360的兼容模式,然而我在自己的电脑上测试的时候是正常的(兼容模式也正常):简单研究了一下360的兼容模式,在360的兼 ...
- php构造函数的继承方法
第一种情况:子类没有定义构造函数时,默认继承.例子: ? 1 2 3 4 5 6 7 8 9 10 11 12 <?php class A{ public $name; function _ ...
- python3字符串属性(二)
1.S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise ...