前方高能,请准备好小板凳,本文篇幅很长,由于是初学,如有不合适的还请大神指导。
最近在研究C#连接Mysql,并实现数据的读写,发现里面还有很多需要注意的,研究过程也遇到不少问题,现在将本人研究的成果分享出来,供需要的朋友学习,最终界面如下图所示,左边为数据写入的功能区(将datagridview控件的数据写入到数据库文件中),右边为数据读取与编辑、添加、查询、删除功能区(将数据库文件读取到datagridview控件中,并实现datagridview控件的编辑能够映射到数据库文件中同步更改)。话不多说,下面直接上代码。
1. 将表格数据写入到数据库
主要功能是根据数据库名称,表格名称将随机生成的datagridview控件中的数据写入到数据库文件中。下面看详细步骤。
1.1 第1步:定义一个Person类
定义这个类的主要目的呢就是后面需要将数据存放到该类中,然后再将该类与datagridview进行数据绑定。
public class Person
{
private int _num;
public int num
{
get { return _num; }
set { _num = value; }
}
private string _name;
public string name
{
get { return _name; }
set { _name = value; }
}
private string _gender;
public string gender
{
get { return _gender; }
set { _gender = value; }
}
private int _age;
public int age
{
get { return _age; }
set { _age = value; }
}
private int _salary;
public int salary
{
get { return _salary; }
set { _salary = value; }
}
public Person(int num, string name, string gender, int age, int salary)
{
this.num = num;
this.name = name;
this.gender = gender;
this.age = age;
this.salary = salary;
}
}
1.2 第2步:定义随机生成英文名字的方法
该方法用于随机生成所需的人名。
/// <summary>
/// 随机生成英文名字
/// </summary>
/// <returns></returns>
private static string GenerateSurname()
{
string name = string.Empty;
string[] currentConsonant;
string[] vowels = "a,a,a,a,a,e,e,e,e,e,e,e,e,e,e,e,i,i,i,o,o,o,u,y,ee,ee,ea,ea,ey,eau,eigh,oa,oo,ou,ough,ay".Split(',');
string[] commonConsonants = "s,s,s,s,t,t,t,t,t,n,n,r,l,d,sm,sl,sh,sh,th,th,th".Split(',');
string[] averageConsonants = "sh,sh,st,st,b,c,f,g,h,k,l,m,p,p,ph,wh".Split(',');
string[] middleConsonants = "x,ss,ss,ch,ch,ck,ck,dd,kn,rt,gh,mm,nd,nd,nn,pp,ps,tt,ff,rr,rk,mp,ll".Split(','); // Can't start
string[] rareConsonants = "j,j,j,v,v,w,w,w,z,qu,qu".Split(',');
Random rng = new Random(Guid.NewGuid().GetHashCode());
int[] lengthArray = new int[] { 2, 2, 2, 2, 2, 2, 3, 3, 3, 4 }; //Favor shorter names but allow longer ones
int length = lengthArray[rng.Next(lengthArray.Length)];
for (int i = 0; i < length; i++)
{
int letterType = rng.Next(1000);
if (letterType < 775) currentConsonant = commonConsonants;
else if (letterType < 875 && i > 0) currentConsonant = middleConsonants;
else if (letterType < 985) currentConsonant = averageConsonants;
else currentConsonant = rareConsonants;
name += currentConsonant[rng.Next(currentConsonant.Length)];
name += vowels[rng.Next(vowels.Length)];
if (name.Length > 4 && rng.Next(1000) < 800) break; //Getting long, must roll to save
if (name.Length > 6 && rng.Next(1000) < 950) break; //Really long, roll again to save
if (name.Length > 7) break; //Probably ridiculous, stop building and add ending
}
int endingType = rng.Next(1000);
if (name.Length > 6)
endingType -= (name.Length * 25); //Don't add long endings if already long
else
endingType += (name.Length * 10); //Favor long endings if short
if (endingType < 400) { } // Ends with vowel
else if (endingType < 775) name += commonConsonants[rng.Next(commonConsonants.Length)];
else if (endingType < 825) name += averageConsonants[rng.Next(averageConsonants.Length)];
else if (endingType < 840) name += "ski";
else if (endingType < 860) name += "son";
else if (Regex.IsMatch(name, "(.+)(ay|e|ee|ea|oo)$") || name.Length < 5)
{
name = "Mc" + name.Substring(0, 1).ToUpper() + name.Substring(1);
return name;
}
else name += "ez";
name = name.Substring(0, 1).ToUpper() + name.Substring(1); //Capitalize first letter
return name;
}
1.3 第3步:初始化datagridview表
为datagridview表格随机生成内容,总行数随机、人名随机、性别随机、年龄随机、薪资随机。
/// <summary>
/// 【方法】初始化数据表
/// </summary>
/// <param name="dataGrid">数据表的名称</param>
static void IniDataGridNew(DataGridView dataGrid)
{
// 设置表头居中,其对齐方式一共有10种,包含竖向的顶中底和水平的左中右以及NotSet
dataGrid.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
//设置表头字体样式
dataGrid.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 11);
//设置单元格cell内容居中
dataGrid.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
//设置单元格cell字体样式
dataGrid.RowsDefaultCellStyle.Font = new Font("宋体", 11);
// 随机生成总行数
Random r = new Random();
int rowNum = r.Next(5, 100);
// 定义相关变量
List<Person> person = new List<Person>();
Random r1 = new Random(); // 生成性别的随机数
Random r2 = new Random(); // 生成年龄的随机数
Random r3 = new Random(); // 生成薪资的随机数
string[] gender = { "Man", "Female" }; // 性别数组
// 生成随机的数据,并绑定到数据表中
for (int i = 0; i < rowNum; i++)
{
Person p = new Person((i + 1), GenerateSurname(), gender[r1.Next(0, 2)], r2.Next(20, 60), r3.Next(15000, 30000));
person.Add(p);
}
dataGrid.DataSource = person;
dataGrid.Columns[0].Width = 80;
}
1.4 第4步:创建数据库
第3步完成后,所需要的数据就已经准备完成。此时编写创建新数据库的函数。
/// <summary>
/// 【方法】创建新的数据库
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">新创建的数据库名称</param>
static void NewDatabase(string dbSource, string dbUid, string dbPwd, string dbName)
{
//创建连接字符串con
MySqlConnection con = new MySqlConnection("Data Source=" + dbSource + ";Persist Security Info=yes;UserId=" + dbUid + "; PWD=" + dbPwd + ";");
//创建数据库的执行语句
MySqlCommand cmd = new MySqlCommand("CREATE DATABASE " + dbName, con);
con.Open();
//执行语句
try
{
int res = cmd.ExecuteNonQuery();
con.Close();
}
catch { }
}
1.5 第5步:创建数据表
基于第4步创建的数据库,为数据库添加数据表。编写创建新数据表的方法。
/// <summary>
/// 【方法】创建数据表
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">新创建的表名称</param>
static void NewDatatable(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
// 获取datagridview中的数据
StringBuilder sb = new StringBuilder();
string colHeader0 = dataGrid.Columns[0].HeaderText;
sb.Append(colHeader0 + " int(11) NOT NULL AUTO_INCREMENT,");
string colHeader1 = dataGrid.Columns[1].HeaderText;
sb.Append(colHeader1 + " TEXT(20),");
string colHeader2 = dataGrid.Columns[2].HeaderText;
sb.Append(colHeader2 + " TEXT(20),");
string colHeader3 = dataGrid.Columns[3].HeaderText;
sb.Append(colHeader3 + " int,");
string colHeader4 = dataGrid.Columns[4].HeaderText;
sb.Append(colHeader4 + " double,");
string tbString = sb.ToString();
//CREATE TABLE mytable (name VARCHAR(20), sex CHAR(1), birth DATE, birthaddr VARCHAR(20));
//创建连接字符串con
MySqlConnection con = new MySqlConnection("Data Source=" + dbSource + ";Persist Security Info=yes;UserId=" + dbUid + "; PWD=" + dbPwd + ";");
string tablecmd = "USE " + dbName + "; CREATE TABLE " + tbName + " ";
string tableText = "(" + tbString + "PRIMARY KEY(" + colHeader0 + "));";
string newTableCMD = tablecmd + tableText; // + tbName + tableText;
MySqlCommand cmd = new MySqlCommand(newTableCMD, con);
con.Open();
int res = cmd.ExecuteNonQuery();
con.Close();
}
1.6 第6步:将数据写入到数据库的表中
编写方法,将datagridview中的数据写入到数据库中指定的table中。
/// <summary>
/// 【方法】将datagridview中的数据写入到数据库的table中。
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">已有数据表名称</param>
/// <param name="dataGrid">datagridview的名称</param>
static void InsertDataToTable(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
//创建连接字符串con
MySqlConnection con = new MySqlConnection("Data Source=" + dbSource + ";Persist Security Info=yes;UserId=" + dbUid + "; PWD=" + dbPwd + ";");
// 打开数据库
string tablecmd = "USE " + dbName + ";";
MySqlCommand cmd = new MySqlCommand(tablecmd, con);
con.Open();
int res = cmd.ExecuteNonQuery();
for (int i = 0; i < dataGrid.RowCount; i++)
{
string data = "INSERT INTO " + tbName + " VALUES (" +
(i+1) + "," +
"'" + dataGrid[1,i].Value + "'" + "," +
"'" + dataGrid[2, i].Value + "'" + "," +
dataGrid[3, i].Value + "," +
dataGrid[4, i].Value + ");";
MySqlCommand cmd1 = new MySqlCommand(data, con);
int res1 = cmd1.ExecuteNonQuery();
}
con.Close();
}
1.7 第7步:随机生成数据
为“随机生成数据”按钮编写clik事件,调用IniDataGridNew方法,可不限次数随机生成数据。
/// <summary>
/// 生成数据表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGenData_Click(object sender, EventArgs e)
{
dgvNew.DataSource = null;
dgvNew.Rows.Clear();
IniDataGridNew(dgvNew);
}
1.8 第8步:将数据写入到数据库
为“数据写入到数据库”按钮编写Click事件,调用NewDatabase方法,NewDatatable方法,InsertDataToTable方法,完成数据写入。
/// <summary>
/// 写入到数据库
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCreateDatabase_Click(object sender, EventArgs e)
{
string dbSource = "localhost";
string dbUid = "root";
string dbPwd = "sjz123456";
string dbName = txtDatabase.Text;
string tbName = txtTable.Text;
NewDatabase(dbSource, dbUid, dbPwd, dbName);
NewDatatable(dbSource, dbUid, dbPwd, dbName, tbName, dgvNew);
InsertDataToTable(dbSource, dbUid, dbPwd, dbName, tbName, dgvNew);
MessageBox.Show("写入完成!");
}
2. 数据库加载及增、删、改、查
该部分主要内容为,从数据库加载指定的数据库下的数据表,并将数据加载中到界面中的datagridview中,用户对datagridview中的数据进行更改时可以同步修改数据库中的内容。
2.1 第1步:导入数据
该步分2个内容,首先编写ReadDatatable方法,用于将数据库中的数据导入到datagridview中。然后再编写“读取数据”按钮的click事件调用ReadDatatable方法。
/// <summary>
/// 【按钮】读取数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnReadData_Click(object sender, EventArgs e)
{
string dbSource = "localhost";
string dbUid = "root";
string dbPwd = "sjz123456";
string dbName = txtDatabase1.Text;
string tbName = txtDataTabla1.Text;
ReadDatatable(dbSource, dbUid, dbPwd, dbName, tbName, dgvView);
MessageBox.Show("读取完成!");
}
/// <summary>
/// 【方法】绑定数据库文件与datagridview控件
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">已有数据表名称</param>
/// <param name="dataGrid">datagridview的名称</param>
static void ReadDatatable(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
string connString = "server=" + dbSource + "; database=" + dbName + "; uid=" + dbUid + "; pwd=" + dbPwd + ";Character Set=utf8;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand comm = new MySqlCommand();
comm.Connection = conn;
try
{
conn.Open();
string sql = "select num ,name,gender,age,salary from " + tbName;
MySqlDataAdapter da = new MySqlDataAdapter(sql, connString);
DataSet ds = new DataSet();
da.Fill(ds, tbName);
dataGrid.DataSource = ds.Tables[tbName];
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "操作数据库出错!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
2.2 第2步:增加数据
该步分2个内容,首先编写AddData方法,用于将界面中的四个文本输入框的内容添加到数据库。然后再编写“添加”按钮的click事件调用AddData方法。
/// <summary>
/// 【按钮】添加数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, EventArgs e)
{
string dbSource = "localhost";
string dbUid = "root";
string dbPwd = "sjz123456";
string dbName = txtDatabase1.Text;
string tbName = txtDataTabla1.Text;
AddData(dbSource, dbUid, dbPwd, dbName, tbName, dgvView);
}
/// <summary>
/// 【方法】添加数据
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">已有数据表名称</param>
/// <param name="dataGrid">datagridview的名称</param>
private void AddData(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
string connString = "server=" + dbSource + "; database=" + dbName + "; uid=" + dbUid + "; pwd=" + dbPwd + ";Character Set=utf8;";
MySqlConnection sqlCon = new MySqlConnection(connString);
sqlCon.Open();
MySqlDataAdapter adapter; //适配器变量
BindingSource bindingSource = new BindingSource();
try
{
string sql = string.Format("INSERT INTO " + tbName + " (name,gender,age,salary) values('{0}','{1}',{2},{3});", txtName.Text, txtGender.Text, txtAge.Text,txtSalary.Text);
MySqlCommand cmd = new MySqlCommand(sql,sqlCon);
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("添加成功");
else
MessageBox.Show("添加失败");
adapter = new MySqlDataAdapter("select * from user", sqlCon);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充数据至ds数据集
bindingSource.DataSource = ds.Tables[0];//绑定数据
dataGrid.DataSource = bindingSource;//为DataGridView数据控件绑定数据
}
catch
{
}
finally
{
sqlCon.Close();
}
}
2.3 第3步:删除数据
该步分2个内容,首先编写DeletData方法,用于将用户选中的数据进行删除。然后再编写“删除”按钮的click事件调用DeletData方法。
/// <summary>
/// 【按钮】删除数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDelet_Click(object sender, EventArgs e)
{
string dbSource = "localhost";
string dbUid = "root";
string dbPwd = "sjz123456";
string dbName = txtDatabase1.Text;
string tbName = txtDataTabla1.Text;
DeletData(dbSource, dbUid, dbPwd, dbName, tbName, dgvView);
}
/// <summary>
/// 【方法】删除数据
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">已有数据表名称</param>
/// <param name="dataGrid">datagridview的名称</param>
private static void DeletData(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
string connString = "server=" + dbSource + "; database=" + dbName + "; uid=" + dbUid + "; pwd=" + dbPwd + ";Character Set=utf8;";
MySqlConnection sqlCon = new MySqlConnection(connString);
try
{
sqlCon.Open();
int index = dataGrid.CurrentCell.RowIndex;
int id = (int)dataGrid.Rows[index].Cells[0].Value;
string sql = "delete from " + tbName + " where num=" + id + "";
MySqlCommand cmd = new MySqlCommand(sql, sqlCon);
int result = cmd.ExecuteNonQuery();
MessageBox.Show(result.ToString());
}
catch
{
}
finally
{
sqlCon.Close();
}
}
2.4 第4步:编辑数据
该步分2个内容,首先编写EditData方法,用于将用户修改的数据更新到数据库中。然后再编写“编辑”按钮的click事件调用EditData方法。
/// <summary>
/// 【按钮】编辑数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnEdit_Click(object sender, EventArgs e)
{
string dbSource = "localhost";
string dbUid = "root";
string dbPwd = "sjz123456";
string dbName = txtDatabase1.Text;
string tbName = txtDataTabla1.Text;
EditData(dbSource, dbUid, dbPwd, dbName, tbName, dgvView);
}
/// <summary>
/// 【方法】编辑数据
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">已有数据表名称</param>
/// <param name="dataGrid">datagridview的名称</param>
private void EditData(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
DataGridViewRow dgr = dataGrid.CurrentRow;//获取当前编辑的行
string connString = "server=" + dbSource + "; database=" + dbName + "; uid=" + dbUid + "; pwd=" + dbPwd + ";Character Set=utf8;";
MySqlConnection sqlCon = new MySqlConnection(connString);
sqlCon.Open();
MySqlDataAdapter adapter; //适配器变量
BindingSource bindingSource = new BindingSource();
try
{
string sql = string.Format("UPDATE " + tbName + " SET name='{0}',gender='{1}',age={2},salary={3} WHERE num={4};",
dgr.Cells[1].Value.ToString(),
dgr.Cells[2].Value.ToString(),
dgr.Cells[3].Value.ToString(),
dgr.Cells[4].Value.ToString(),
dgr.Cells[0].Value.ToString());
MySqlCommand cmd = new MySqlCommand(sql, sqlCon);
int result = cmd.ExecuteNonQuery();
if (result > 0)
MessageBox.Show("修改成功");
else
MessageBox.Show("修改失败");
adapter = new MySqlDataAdapter("select * from user", sqlCon);
DataSet ds = new DataSet();
adapter.Fill(ds);//填充数据至ds数据集
bindingSource.DataSource = ds.Tables[0];//绑定数据
dataGrid.DataSource = bindingSource;//为DataGridView数据控件绑定数据
}
catch
{
}
finally
{
sqlCon.Close();
}
}
2.5 第5步:查询数据
该步分2个内容,首先编写DataQuery方法,用于在数据库中根据界面搜索框中输入的数据进行查找并获取查找到的数据,并将数据以信息窗的形式显示出来。然后再编写“查询”按钮的click事件调用DataQuery方法。
/// <summary>
/// 【按钮】查询数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnQuery_Click(object sender, EventArgs e)
{
string dbSource = "localhost";
string dbUid = "root";
string dbPwd = "sjz123456";
string dbName = txtDatabase1.Text;
string tbName = txtDataTabla1.Text;
DataQuery(dbSource, dbUid, dbPwd, dbName, tbName, dgvView);
}
/// <summary>
/// 【方法】查询数据
/// </summary>
/// <param name="dbSource">服务器名称,如localhost</param>
/// <param name="dbUid">用户名,如root</param>
/// <param name="dbPwd">密码</param>
/// <param name="dbName">已有数据库名称</param>
/// <param name="tbName">已有数据表名称</param>
/// <param name="dataGrid">datagridview的名称</param>
private void DataQuery(string dbSource, string dbUid, string dbPwd, string dbName, string tbName, DataGridView dataGrid)
{
string connString = "server=" + dbSource + "; database=" + dbName + "; uid=" + dbUid + "; pwd=" + dbPwd + ";Character Set=utf8;";
MySqlConnection sqlCon = new MySqlConnection(connString);
string sql = string.Format("select * from " + tbName + " where name like '%{0}%' or gender like '%{0}%' or age like '%{0}%' or salary like '%{0}%';", txtQuary.Text);
MySqlCommand cmd = new MySqlCommand(sql, sqlCon);
//查询结果读取器
MySqlDataReader reader = null;
try
{
//打开连接
sqlCon.Open();
//执行查询,并将结果返回给读取器
reader = cmd.ExecuteReader();
while (reader.Read())
{
string res = "ID=" + reader[0].ToString() + " ,Name=" + reader[1].ToString() + " ,Gender=" +
reader[2].ToString() + " ,Age=" + reader[3].ToString() + " ,salary=" + reader[4].ToString() + ".";
MessageBox.Show(res);
}
}
catch { }
finally
{
reader.Close();
sqlCon.Close();
}
}
至此,所有功能已开发完成。
在开发过程中,搜索了大量的网络资源,但都没有特别全面的,希望我这篇大全资料能够对有需要的朋友提供小小的帮助,而无需到处找一些零散的资源。最后给出该案例中所用的数据库文件,义工参考。
文章来源:https://www.toymoban.com/news/detail-428998.html
完结。 文章来源地址https://www.toymoban.com/news/detail-428998.html
到了这里,关于【C#&Mysql】最全C#连接Mysql: 读、增、删、改、查的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!