MySqlParameter如何使用
时间: 2024-05-04 11:16:56 浏览: 16
MySqlParameter 是用于在 MySQL 数据库中执行参数化查询的类。以下是一个基本的使用示例:
```csharp
using System;
using MySql.Data.MySqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Server=localhost;Database=mydatabase;Uid=myusername;Pwd=mypassword;";
string query = "SELECT * FROM users WHERE age > @age";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@age", 18); // 添加参数
connection.Open();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Name: {0}, Age: {1}", reader.GetString(0), reader.GetInt32(1));
}
}
}
}
}
}
```
在这个示例中,我们使用 MySqlCommand 和 MySqlDataReader 来执行查询操作。我们使用了 AddWithValue 方法来添加一个参数,它将参数的名称和值一起传递。在查询中,我们使用了 @age 参数,这个参数的值由 AddWithValue 方法设置。
这是一个基本的 MySqlParameter 的使用示例。在实际应用中,您可能需要使用更多的参数,还可以设置参数的数据类型、长度等属性。
相关推荐
![](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)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)