C#接口实现mysql语句
时间: 2023-08-21 10:07:09 浏览: 118
下面是一个使用C#实现MySQL语句的示例代码:
```csharp
using System;
using MySql.Data.MySqlClient;
public interface IDatabaseService
{
bool Connect(string connectionString);
bool Disconnect();
bool ExecuteNonQuery(string query);
MySqlDataReader ExecuteReader(string query);
}
public class MySqlDatabaseService : IDatabaseService
{
private MySqlConnection connection;
public bool Connect(string connectionString)
{
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error connecting to MySQL: " + ex.Message);
return false;
}
}
public bool Disconnect()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error disconnecting from MySQL: " + ex.Message);
return false; }
}
public bool ExecuteNonQuery(string query)
{
MySqlCommand command = new MySqlCommand(query, connection);
try
{
command.ExecuteNonQuery();
return true;
}
catch (MySqlException ex)
{
Console.WriteLine("Error executing non-query: " + ex.Message);
return false;
}
}
public MySqlDataReader ExecuteReader(string query)
{
MySqlCommand command = new MySqlCommand(query, connection);
try
{
return command.ExecuteReader();
}
catch (MySqlException ex)
{
Console.WriteLine("Error executing reader: " + ex.Message);
return null;
}
}
}
public class Program
{
public static void Main()
{
string connectionString = "your_connection_string_here";
IDatabaseService databaseService = new MySqlDatabaseService();
if(databaseService.Connect(connectionString))
{
// 执行查询语句
string query = "SELECT * FROM table_name";
MySqlDataReader reader = databaseService.ExecuteReader(query);
if(reader != null)
{
while(reader.Read())
{
// 处理查询结果
string column1 = reader.GetString(0);
int column2 = reader.GetInt32(1);
Console.WriteLine("Column1: " + column1 + ", Column2: " + column2);
}
reader.Close();
}
// 执行非查询语句
string insertQuery = "INSERT INTO table_name (column1, column2) VALUES ('value1', 2)";
bool success = databaseService.ExecuteNonQuery(insertQuery);
if(success)
{
Console.WriteLine("Insert query executed successfully.");
}
databaseService.Disconnect();
}
Console.ReadLine();
}
}
```
在上述代码中,我们定义了一个`IDatabaseService`接口,其中包含连接数据库、断开连接、执行非查询语句和执行查询语句的方法。然后,我们实现了一个`MySqlDatabaseService`类,该类通过`MySqlConnection`对象连接到MySQL数据库并实现了`IDatabaseService`接口的方法。
在`Main`方法中,我们创建了一个`MySqlDatabaseService`对象,并调用了`Connect`方法来连接到数据库。如果连接成功,我们可以执行查询语句和非查询语句。在执行查询语句时,我们使用`ExecuteReader`方法返回一个`MySqlDataReader`对象,并通过循环读取查询结果。在执行非查询语句时,我们使用`ExecuteNonQuery`方法执行插入语句,并检查返回值来判断是否执行成功。最后,我们调用`Disconnect`方法断开与数据库的连接。
请注意,你需要将`your_connection_string_here`替换为你自己的MySQL连接字符串。这个连接字符串应包含正确的数据库服务器地址、用户名、密码和数据库名称。
阅读全文