C#联合MySQL增删查改
时间: 2024-02-05 09:08:12 浏览: 91
以下是C#联合MySQL进行增删查改的示例代码:
1. 连接MySQL数据库:
```csharp
using MySql.Data.MySqlClient;
string connectionString = "server=localhost;user=root;database=mydatabase;password=mypassword";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
```
2. 插入数据:
```csharp
string insertQuery = "INSERT INTO student (name) VALUES (@name)";
MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection);
insertCommand.Parameters.AddWithValue("@name", "John");
insertCommand.ExecuteNonQuery();
```
3. 查询数据:
```csharp
string selectQuery = "SELECT * FROM student";
MySqlCommand selectCommand = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32("id");
string name = reader.GetString("name");
Console.WriteLine("ID: " + id + ", Name: " + name);
}
reader.Close();
```
4. 更新数据:
```csharp
string updateQuery = "UPDATE student SET name = @newName WHERE id = @id";
MySqlCommand updateCommand = new MySqlCommand(updateQuery, connection);
updateCommand.Parameters.AddWithValue("@newName", "Jane");
updateCommand.Parameters.AddWithValue("@id", 1);
updateCommand.ExecuteNonQuery();
```
5. 删除数据:
```csharp
string deleteQuery = "DELETE FROM student WHERE id = @id";
MySqlCommand deleteCommand = new MySqlCommand(deleteQuery, connection);
deleteCommand.Parameters.AddWithValue("@id", 1);
deleteCommand.ExecuteNonQuery();
```
6. 关闭数据库连接:
```csharp
connection.Close();
```
阅读全文