No connection associated with this command
时间: 2024-04-12 12:32:02 浏览: 40
如果您在执行 `ExecuteNonQuery()` 方法时遇到 "No connection associated with this command" 错误,可能是由于连接未正确打开或已关闭导致的。您可以尝试使用以下修改后的代码来解决该问题:
```csharp
using System;
using System.Data.SQLite;
namespace SQLiteExample
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=your_database_file.db;Version=3;";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
string tableName = "your_table_name";
string sql = $"PRAGMA table_info({tableName})";
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string columnName = reader["name"].ToString();
string dropColumnSql = $"ALTER TABLE {tableName} DROP COLUMN {columnName}";
using (SQLiteConnection connection2 = new SQLiteConnection(connectionString))
{
connection2.Open();
using (SQLiteCommand dropColumnCommand = new SQLiteCommand(dropColumnSql, connection2))
{
dropColumnCommand.ExecuteNonQuery();
}
connection2.Close();
}
}
}
}
}
Console.WriteLine("All columns removed successfully.");
Console.ReadLine();
}
}
}
```
在此修改后的代码中,我们为每个删除操作创建了一个新的连接,并在执行完操作后手动关闭连接。这样可以确保每个操作都在一个打开的连接上执行,避免了 "No connection associated with this command" 错误。请确保将 `your_database_file.db` 替换为您的SQLite数据库文件的路径和名称,将 `your_table_name` 替换为您要删除列的表名。运行此代码后,它应该能够成功删除指定表的所有列,并输出成功消息。