網(wǎng)站首頁 編程語言 正文
一、界面布局
界面中有一個(gè)dataGridview、兩個(gè)Button、兩個(gè)Label和兩個(gè)TextBox。
二、定義數(shù)據(jù)庫操作的公共類
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) // 創(chuàng)建連接
{
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) // 重載 創(chuàng)建連接
{
try
{
m_ClientsqlConn.Close();
m_ClientsqlConn.ConnectionString = connStr;
m_ClientsqlConn.Open();
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
public DataTable GetDataTable(string SQLstr) // 獲取DataTable 一個(gè)表
{
Console.Write("zcn==獲取數(shù)據(jù)庫連接,打開數(shù)據(jù)庫");
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==獲取數(shù)據(jù)庫連接,打開數(shù)據(jù)庫異常異常");
//MessageBox.Show( ee.Message);
m_logclass.WriteLogFilein(ee.Message, "GetDataTable.txt");
return null;
}
finally
{
m_ClientsqlConn.Close();
}
}
public DataTable GetDataTableUsing(string SQLstr) // 獲取DataTable 一個(gè)表
{
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) //根據(jù)某一列的名字 獲取某個(gè)集合中該列的所有值
{
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) //根據(jù) datatable 獲取每一行的數(shù)據(jù)的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) //根據(jù)ID號(hào) 返回對(duì)應(yīng)行的 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 一個(gè)表中一行
{
MySqlDataAdapter da = new MySqlDataAdapter(SQLstr, m_ClientsqlConn);
DataTable resultDS = new DataTable();
da.Fill(resultDS);
return resultDS;
}
public DataTable GetDataSet_to_Table(string SQLstr) // 獲取 dataset 多個(gè)表中 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) //根據(jù) 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) // 根據(jù)
{
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() // 參數(shù)類型 不同數(shù)據(jù)庫連接
{
m_ClientsqlConn.Close();
}
}
}
三、在界面中操作數(shù)據(jù)庫方法
ps:數(shù)據(jù)庫的配置信息保存在Config.ini文件中,如果僅是測(cè)試用的話,可以直接在
m_DataBase = new DBCtrl(ipstr, namestr, usernamestr, passwordstr);
處輸入ip地址、數(shù)據(jù)庫名、數(shù)據(jù)庫用戶名和密碼即可
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文件函數(shù)
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值設(shè)為空
private void TextBoxNull()
{
textBox1.Text = "";
textBox2.Text = "";
}
//設(shè)置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響應(yīng)事件
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();
}
}
//點(diǎn)擊修改按鈕響應(yīng)事件
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("輸出當(dāng)前選中數(shù)據(jù)行:" + currentIndex);
flag = m_DataBase.deleteRowfor("device_info1", currentIndex);
if (flag)
{
MessageBox.Show("刪除成功!");
initDataTable();
}
else
{
MessageBox.Show("刪除失敗!");
}
}
}
}
原文鏈接:https://blog.csdn.net/zcn596785154/article/details/81283722
相關(guān)推薦
- 2022-09-15 c語言實(shí)現(xiàn)數(shù)組循環(huán)左移m位_C 語言
- 2022-09-06 python?OpenCV的imread不能讀取中文路徑問題及解決_python
- 2022-08-15 使用enum關(guān)鍵字定義的枚舉類實(shí)現(xiàn)接口的情況
- 2022-02-17 H5移動(dòng)端點(diǎn)擊出現(xiàn)背景藍(lán)色框的解決方案
- 2023-01-26 redis性能優(yōu)化之生產(chǎn)中實(shí)際遇到的問題及排查總結(jié)_Redis
- 2023-03-13 Android?Hilt依賴注入的使用講解_Android
- 2023-07-06 golang中time包時(shí)間處理
- 2023-06-17 Python利用plotly繪制正二十面體詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支