本文主要介绍通过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表格内数据与数据库交互的更多相关文章

  1. 如何将Excl内数据导入数据库?

    最近有个Excl表格内的数据需要导入SQL Server数据库内,使用SQL Server Management Studio客户端图形界面操作了一番,步骤还挺多,感觉有必要分享给大家一下,顺便自己也 ...

  2. BootStrap table动态增删改表格内数据

    1:添加一个[操作]列   { title: "操作", align: 'center', valign: 'middle', width: 160, // 定义列的宽度,单位为像 ...

  3. js遍历获取表格内数据方法

    1.一般的表格结构如下 <table> <tr> <td>id</td> <td>name</td> </tr> & ...

  4. 从Excel表格导入数据到数据库

    数据库:SQL 1.小数据直接粘贴 2.用导入向导 3.用SSIS包 4.用SQL语句 现在详细说一下第4种方法,以.xlsx文件为例 .xlsx文件需要用provider“Microsoft.ACE ...

  5. Android系统编程入门系列之应用内数据保存数据库

    上篇文章已经介绍了如何使用SharedPreferences存储键值对形式的轻量级数据,对于那些相同结构的多组数据,类似于存储Java中定义的类的多个对象属性值,如果按照键值对的形式一条条读写,需要分 ...

  6. Python+Selenium+Mysql(动态获取数据,数据库交互)

    一.创建数据库连接 #!coding:utf-8 import pymysql ''' Python3之后不再支持MySQLdb的方式进行访问mysql数据库: 可以采用pymysql的方式 连接方式 ...

  7. 使用openpyxl模块将Excel中的数据导入数据库

    这里将不介绍openpyxl模块的详细操作. 主要就是记录一个使用openpyxl模块将Excel表格的数据导入数据库中的实例. from openpyxl import load_workbook ...

  8. 怎么把excel表格内的数据导入数据库?

    第一种方法: 思路:想要把excel表格内的数据直接导入数据库不是那么容易,可以把excel表格另存为.csv格式的文档(特点:内容以逗号分割):然后通过一系列的文档操作函数处理成为一个二维数组,然后 ...

  9. Linqpad使用(调试Linq、结合linq调试业务场景、表格内编辑数据)

      linqpad是一款linq语句调试工具,功能如下: 1.直接执行linq语句并查看生成的原生sql语句 2.可结合linq+C#代码进行业务场景调试 3.表格内直接新增.修改.删除数据 4.直接 ...

随机推荐

  1. 搜索ABAP程序代码中的字符串

    标准程序名:RPR_ABAP_SOURCE_SCAN /BEV1/NERM07DOCS

  2. python3 生成随即激活码

    import string import random #激活码中的字符和数字 field = string.ascii_letters + string.digits #获得四个字母和数字的随即组合 ...

  3. iOS UILabel 省略号 不变色 问题处理

    在我们公司 应用 4.1版本 我发现一个很有趣的问题 ,  当我修改 label 的 textColor  (默认单行情况)为黑色之外的颜色   省略号依然为黑色, 这个在iOS 7 iOS8.1 i ...

  4. python3 mysql 多表查询

    python3 mysql 多表查询 一.准备表 创建二张表: company.employee company.department #建表 create table department( id ...

  5. debian下使用ft232为stm32f429i-discovery烧写uboot和uImage

    操作系统:debian 软件: openocd  minicom 硬件:  MiniUSB线.stm32f429i-discovery, WaveShare FT232串口模块(可以在淘宝上买到) 关 ...

  6. Spring Cloud之网关

    接口的分类: 开放接口:可以授权一些接口口OAuth2.0协议方式  第三方联合登录 内部接口:  一般只能在局域网中进行访问,服务与服务之间关系都在同一个微服务系统中.目的是为了保证安全问题 接口设 ...

  7. O(1) 快速乘

    有一些毒瘤题,数据大小不光会炸\(int\),有时甚至会炸\(long long\).这时一个\(O(1)\)的防爆乘就很重要了 \(a*b%p\)可以转化为\(a*b-[a*b/p]*p\) 这里用 ...

  8. Spark- Checkpoint原理剖析

    Checkpoint,是Spark 提供的一个比较高级的功能.有的时候,比如说,我们的 Spark 应用程序,特别的复杂,然后从初始的RDD开始,到最后拯个应用程序完成,有非常多的步骤,比如超过20个 ...

  9. 内存表 ClientDataSet CreateDataSet

    unit Form_Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, F ...

  10. poj 1080 Human Gene Functions(lcs,较难)

    Human Gene Functions Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 19573   Accepted:  ...