用c sharp 编写一个关于mysql 的增删改查
时间: 2023-06-12 20:06:36 浏览: 84
下面是一个简单的示例代码,用C#连接MySQL数据库,实现增删改查:
```
using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
public class MySqlHelper
{
//数据库连接字符串
private static string connStr = "server=localhost;user=root;password=root;database=test;";
//执行查询操作,返回DataSet结果集
public static DataSet ExecuteDataSet(string sql)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
DataSet ds = new DataSet();
try
{
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(sql, conn);
da.Fill(ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}
//执行增删改操作,返回受影响的行数
public static int ExecuteNonQuery(string sql)
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
int count = 0;
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, conn);
count = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return count;
}
}
}
```
查询操作示例:
```
string sql = "SELECT * FROM students";
DataSet ds = MySqlHelper.ExecuteDataSet(sql);
foreach (DataRow row in ds.Tables[0].Rows)
{
string name = row["name"].ToString();
int age = Convert.ToInt32(row["age"]);
Console.WriteLine("姓名:{0},年龄:{1}", name, age);
}
```
插入操作示例:
```
string sql = "INSERT INTO students(name, age) VALUES('张三', 18)";
int count = MySqlHelper.ExecuteNonQuery(sql);
Console.WriteLine("插入了{0}行数据", count);
```
更新操作示例:
```
string sql = "UPDATE students SET age=20 WHERE name='张三'";
int count = MySqlHelper.ExecuteNonQuery(sql);
Console.WriteLine("更新了{0}行数据", count);
```
删除操作示例:
```
string sql = "DELETE FROM students WHERE name='张三'";
int count = MySqlHelper.ExecuteNonQuery(sql);
Console.WriteLine("删除了{0}行数据", count);
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)