C#如何在窗体程序中操作数据库数据
作者:596785154 发布时间:2024-01-22 13:31:41
标签:C#,窗体程序,数据库,数据
一、界面布局
界面中有一个dataGridview、两个Button、两个Label和两个TextBox。
二、定义数据库操作的公共类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using MySql.Data.MySqlClient;
namespace TemSys
{
public class DBCtrl
{
private MySqlConnection m_ClientsqlConn;
public DBCtrl() // 连接类型
{
m_ClientsqlConn = new MySqlConnection();
try
{
m_ClientsqlConn.Dispose();
m_ClientsqlConn.Close();
m_ClientsqlConn.ConnectionString = "Database=dbName;Data Source=localhost;User Id=root;Password=123;charset=utf8";
m_ClientsqlConn.Open();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
public DBCtrl(string IP, string DBname, string Uname, string Pword) // 创建连接
{
m_ClientsqlConn = new MySqlConnection();
try
{
m_ClientsqlConn.Dispose();
m_ClientsqlConn.Close();
m_ClientsqlConn.ConnectionString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};charset=utf8", DBname, IP, Uname, Pword);
m_ClientsqlConn.Open();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
public void DBConn(string connStr) // 重载 创建连接
{
try
{
m_ClientsqlConn.Close();
m_ClientsqlConn.ConnectionString = connStr;
m_ClientsqlConn.Open();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
public DataTable GetDataTable(string SQLstr) // 获取DataTable 一个表
{
Console.Write("zcn==获取数据库连接,打开数据库");
try
{
if (m_ClientsqlConn.State == ConnectionState.Open)
m_ClientsqlConn.Close();
m_ClientsqlConn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn);
DataTable resultDS = new DataTable();
da.Fill(resultDS);
return resultDS;
}
catch (Exception ee)
{
Console.Write("zcn==获取数据库连接,打开数据库异常异常");
//MessageBox.Show( ee.Message);
m_logclass.WriteLogFilein(ee.Message, "GetDataTable.txt");
return null;
}
finally
{
m_ClientsqlConn.Close();
}
}
public DataTable GetDataTableUsing(string SQLstr) // 获取DataTable 一个表
{
using (MySqlConnection m_ClientsqlConn = new MySqlConnection())
{
}
try
{
if (m_ClientsqlConn.State == ConnectionState.Open)
m_ClientsqlConn.Close();
m_ClientsqlConn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn);
DataTable resultDS = new DataTable();
da.Fill(resultDS);
return resultDS;
}
catch (Exception ee)
{
//MessageBox.Show( ee.Message);
return null;
}
}
public List<string> GetStringListfor(string lineName,DataTable dt) //根据某一列的名字 获取某个集合中该列的所有值
{
List<string> list = new List<string>();
foreach (DataRow dr in dt.Rows)
{
list.Add((string)dr[lineName]);
}
return list;
}
public List<DataRow> GetDataRowfor(DataTable dt) //根据 datatable 获取每一行的数据的datarow
{
List<DataRow> list = new List<DataRow>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr);
}
return list;
}
/*
public DataRow GetDataRowfor(string tablename,string ID) //根据ID号 返回对应行的 DataRow
{
string ss = "select * from " + tablename + " where ID = \'"+ID +"\'";
DataRow dr = new DataRow();
DataTable dt = GetDataTable(ss);
dr = dt.Rows[0];
return dr;
}
*/
public DataTable GetDataTableOneLine(string SQLstr) // 获取DataTable 一个表中一行
{
MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn);
DataTable resultDS = new DataTable();
da.Fill(resultDS);
return resultDS;
}
public DataTable GetDataSet_to_Table(string SQLstr) // 获取 dataset 多个表中 table
{
try
{
MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch
{
return null;
}
}
public Boolean InsertDBase(string insString)
{
try
{
if (m_ClientsqlConn.State == ConnectionState.Open)
m_ClientsqlConn.Close();
m_ClientsqlConn.Open();
MySqlCommand sqlcomd = new MySqlCommand(insString, m_ClientsqlConn);
sqlcomd.ExecuteNonQuery();
return true;
}
catch (Exception ee)
{
return false;
}
finally
{
m_ClientsqlConn.Close();
}
}
public Boolean deleteRowfor(string tablename,int deleteID) //根据 ID 删除指定行
{
try
{
string ss ="delete from "+ tablename +" where ID = "+ deleteID;
if (m_ClientsqlConn.State == ConnectionState.Open)
m_ClientsqlConn.Close();
m_ClientsqlConn.Open();
MySqlCommand sqlcmd = new MySqlCommand(ss, m_ClientsqlConn);
sqlcmd.ExecuteNonQuery();
return true;
}
catch(Exception ee)
{
return false;
}
}
public Boolean ModifyRowfor(string modifystr,string modifyID) // 根据
{
try
{
string ss = modifystr + " where id = " + modifyID;
if (m_ClientsqlConn.State == ConnectionState.Open)
m_ClientsqlConn.Close();
m_ClientsqlConn.Open();
MySqlCommand sqlcmd = new MySqlCommand(ss, m_ClientsqlConn);
sqlcmd.ExecuteNonQuery();
return true;
}
catch (Exception ee)
{
return false;
}
finally
{
m_ClientsqlConn.Close();
}
}
public void CloseDBase() // 参数类型 不同数据库连接
{
m_ClientsqlConn.Close();
}
}
}
三、在界面中操作数据库方法
ps:数据库的配置信息保存在Config.ini文件中,如果仅是测试用的话,可以直接在
m_DataBase = new DBCtrl(ipstr, namestr, usernamestr, passwordstr);
处输入ip地址、数据库名、数据库用户名和密码即可
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TemSys
{
public partial class ModifyDevice : Form
{
[DllImport("kernel32")] //读写ini文件函数
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
DataTable dt = new DataTable();
private DBCtrl m_DataBase;
public ModifyDevice()
{
InitializeComponent();
}
//将所有的textBox值设为空
private void TextBoxNull()
{
textBox1.Text = "";
textBox2.Text = "";
}
//设置Lab值
private void labelshow()
{
label1.Text = dataGridView1.Columns[0].HeaderText;
label2.Text = dataGridView1.Columns[12].HeaderText;
}
//初始化界面
private void ModifyDevice_Load(object sender, EventArgs e)
{
StringBuilder retval = new StringBuilder();
GetPrivateProfileString("DBConfig", "dbip", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
string ipstr = retval.ToString();
GetPrivateProfileString("DBConfig", "dbname", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
string namestr = retval.ToString();
GetPrivateProfileString("DBConfig", "dbusername", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
string usernamestr = retval.ToString();
GetPrivateProfileString("DBConfig", "dbpassword", "", retval, 20, AppDomain.CurrentDomain.BaseDirectory + "Config.ini");
string passwordstr = retval.ToString();
m_DataBase = new DBCtrl(ipstr, namestr, usernamestr, passwordstr);
initDataTable();
}
private void initDataTable()
{
string ssp = string.Format("select * from device_info1");
dt = m_DataBase.GetDataTable(ssp);
dataGridView1.DataSource = dt;
labelshow();
}
//双击dataGridView响应事件
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
string index = dataGridView1.CurrentRow.Cells[0].Value.ToString();
if (label1.Text == "id")
{
string ssp = string.Format("select * from device_info1 where id='" + index + "'");
dt = m_DataBase.GetDataTable(ssp);
//DataRow row = dt.Rows[0];
textBox1.Text = dt.Rows[0]["id"].ToString();
textBox2.Text = dt.Rows[0]["number"].ToString();
}
}
//点击修改按钮响应事件
private void btnModify_Click(object sender, EventArgs e)
{
bool flag = false;
string ssp = string.Format("update device_info1 set number='" + textBox2.Text + "'");
flag = m_DataBase.ModifyRowfor(ssp, textBox1.Text);
if (flag)
{
MessageBox.Show("修改成功!");
initDataTable();
}
else
{
MessageBox.Show("修改失败!");
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
bool flag = false;
int currentIndex = (int)dataGridView1.CurrentRow.Cells[0].Value;
Console.WriteLine("输出当前选中数据行:" + currentIndex);
flag = m_DataBase.deleteRowfor("device_info1", currentIndex);
if (flag)
{
MessageBox.Show("删除成功!");
initDataTable();
}
else
{
MessageBox.Show("删除失败!");
}
}
}
}
来源:https://blog.csdn.net/zcn596785154/article/details/81283722
0
投稿
猜你喜欢
- 变量什么是变量?变量是在程序运行时,能存储计算结果或能表示值得抽象概念。简单地说,变量就是在程序运行时,记录数据用的变量定义格式:变量名称=
- 如下所示:#python解决字符串倒序输出def string_reverse(m): num=len(m) a=[] for i in r
- 最近在看python的算法书,之前在年前买的书,一直在工作间隙的时候,学习充电,终于看到这本书,但是确实又有点难,感觉作者写的代码太炫技 了
- 前言最近在功能性测试的过程中,需要在Python环境下用OpenCV读取网络摄像头的视频流,接着用目标检测器进行视屏帧的后续处理。在测试过程
- 简介单例模式是创建型对象的一种,用于如何优雅的创建对象。让一个类最多产生一个对象。场景只需要一个对象就能解决并且要使用多次的场景,比如框架的
- 程序说明:本程序实现将开发程序服务器中的打包文件通过该脚本上传到正式生产环境(注:生产环境和开发环境不互通)程序基本思路:将开发环境中的程序
- 从一个问题说起五年前在腾讯的时候,发现分页场景下,mysql请求速度非常慢。数据量只有10w的情况下,select xx from 单机大概
- 一、开发时管理数据库遇到的问题:现在开发一般都是团队开发,这样就会出现项目同步的问题,代码同步可以通过SVN工具管理起来,那数据库同步怎么办
- 目录爬取目标站点分析编码时间爬取结果展示爬取目标站点分析本次采集的目标站点为:https://www.zaih.com/falcon/men
- 一、查询条件精确,针对有参数传入情况 二、SQL逻辑执行顺序 FROM-->JOIN-->WHERE-->GROUP--&
- Batch Normalization和Dropout是深度学习模型中常用的结构。但BN和dropout在训练和测试时使用却不相同。Batc
- 代码如下:---在仓储管理中经常会碰到的一个问题 一、关于LIFO与FIFO的简单说明 ---FIFO: First in, First o
- 一、关联规则概述1993年,Agrawal等人在首先提出关联规则概念,迄今已经差不多30年了,在各种算法层出不穷的今天,这算得上是老古董了,
- 本文实例讲述了Python实现监控程序执行时间并将其写入日志的方法。分享给大家供大家参考。具体实现方法如下:# /usr/bin/pytho
- 一个3层嵌套列表mm=["a",["b","c",["inner&qu
- 本篇阅读的代码实现了将输入的数字转化成一个列表,输入数字中的每一位按照从左到右的顺序成为列表中的一项。本篇阅读的代码片段来自于30-seco
- 废话不多说了,直接步入正题,一个完整的神经网络一般由三层构成:输入层,隐藏层(可以有多层)和输出层。本文所构建的神经网络隐藏层只有一层。一个
- asp如何实现当前月份距离以前某个时间的月份数 如今天是2011年1月份,我想知道离2010年3月,计算这中间一共是几个月 最佳答案 <
- 本文实例讲述了Python列表推导式与生成器用法。分享给大家供大家参考,具体如下:1. 先看两个列表推导式def t1(): f
- 1 旖旎风景马上虎年了,也是我的生肖年,很激动!(不小心暴露了年龄,哈哈哈......),这里先给大家拜年啦,祝大家虎年快乐,虎年爆富!&n