本文主要介绍通过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. 3.07课·········if分支语句

    语句分类:顺序语句,选择语句(分支语句),循环语句 分支语句:(一)if(表达式) //表达式返回值是True或False{}说明:1.表达式返回的是bool值:2.小括号和花括号后面不需要加分号. ...

  2. c#命名规则参考

    命名规则参考:1.从组件类型名中移去T前缀.例如TButton变成Button.2.除了第一个元音,删去所有元音字母.例如,Button变成bttn,Edit变成edt.3.压缩双字母.例如,bttn ...

  3. 【leetcode刷题笔记】Valid Number

    Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...

  4. nginx 搭建虚拟主机

    一.排错三部曲 第一步在客户端上ping服务端ip  ping 10.0.0.8 第二部在客户端上telnet服务器端IP.端口  telnet 10.0.0.8 第三部在客户端使用wget命令检测 ...

  5. 算法(Algorithms)第4版 练习 2.2.11(2)

    关键代码: private static void sort(Comparable[] input, int lo, int hi) { if(lo >= hi)//just one entry ...

  6. iOS App被拒原因以及解决方案总结。

    Guideline 1.2 - Safety - User Generated Content Your app enables the display of user-generated conte ...

  7. mvc购物车项目(2)

    为了避免数据冗余,我们可以把共同的信息,抽出建立一个单独的表,把不是共有的信息,建立一张单独表. 订单表分为两个表 create table orders( id number primary key ...

  8. php数组转换成js可用的数组的两种方式

    1.如果你理解JSON数据格式的话,这个问题就异常简单: <?php $a =array('1','2','3'); ?> <script language="javasc ...

  9. 实现stack 加上·getMin功能 时间复杂度为O(n)

    package com.hzins.suanfa; import java.util.Stack; /** * 实现stack 加上·getMin功能 时间复杂度为O(n) * @author Adm ...

  10. MFC动态创建

    每个继承自CObject的对象并不会有与之对应的CRuntimeClass与之对应,除非使用了宏DECLARE_DYNAMIC\DECLARE_DYNCREATE\DECLARE_SERIAL. 这三 ...