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.直接 ...
随机推荐
- docker centos yum 源
aliyun yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.rep ...
- ubuntu 13.04 设定静态IP
切换到root用户,然后进入/etc/network目录.备份interfaces文件(备份文件是一个好习惯) 下面编辑interfaces文件,添加如下语句: # Assgin static IP ...
- IONIC3 打包安卓apk详细过程(大量图文)
经历三天的踩坑,跳坑,相信绝大多数的问题都已经覆盖到了,请仔细按照流程来对照操作及检查. 1.基本依赖环境 nodejs环境 (作为一个前端相信你已经有了) 最好提前配置好node的环境变量,便于全 ...
- vue页面性能优化方案
个人在项目中用到的页面性能优化的方式总结. 一.均衡页面加载文件的大小和数量 1.项目中小图片图片转base64,通过工具如webpack进行图片压缩,文件进行压缩混淆等 2.vue-router 懒 ...
- 用Java实现断点续传的基本思路和代码
用Java实现断点续传的基本思路和代码 URL url = new URL(http://www.oschina.net/no-exist.zip); HttpURLConnection http ...
- hadoop自带例子SecondarySort源码分析MapReduce原理
这里分析MapReduce原理并没用WordCount,目前没用过hadoop也没接触过大数据,感觉,只是感觉,在项目中,如果真的用到了MapReduce那待排序的肯定会更加实用. 先贴上源码 pac ...
- 简化Hadoop命令
1. 安装客户端(通过端用户可以方便的和集群交互) 2. 简化Hadoop命令 修改~/.bashrcalias hadoop='/home/work/hadoop/client/hadoop-cli ...
- 织梦dedecms 调用文章图片数功能
function BodyImgNum($aid) { global $dsql; $sql = "select aid,body from dede_addonarticle where ...
- castle windsor学习----- Referencing types in XML 在xm文件中引用类型
当从xml引用installer的语法如下 <install type="Acme.Crm.Infrastructure.ServicesInstaller, Acme.Crm.Inf ...
- 算法(Algorithms)第4版 练习 1.3.2
was best times of the was the it (1 left on stack)