Example: Using IDbCommand with SQLite
// Install System.Data.SQLite via NuGet before running this example.
using System;
using System.Data;
using System.Data.SQLite;
class Program
{
static void Main()
{
using (IDbConnection conn = new SQLiteConnection("Data Source=:memory:"))
{
conn.Open();
// Create table
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "CREATE TABLE Employees(Id INTEGER PRIMARY KEY, Name TEXT, Salary REAL);";
cmd.ExecuteNonQuery();
}
// Insert data
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Employees(Name, Salary) VALUES(@name, @salary);";
var pName = cmd.CreateParameter();
pName.ParameterName = "@name";
pName.Value = "Alice";
cmd.Parameters.Add(pName);
var pSalary = cmd.CreateParameter();
pSalary.ParameterName = "@salary";
pSalary.Value = 75000;
cmd.Parameters.Add(pSalary);
cmd.ExecuteNonQuery();
}
// Query data
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT Id, Name, Salary FROM Employees;";
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)} - {reader.GetString(1)} - {reader.GetDecimal(2)}");
}
}
}
}
}
}
This example demonstrates how to create a table, insert a row, and read the data using the IDbCommand
interface.