OleDbParameterを使用してアクセス先のテーブルを作成します

データベースに接続し、OleDbCommandオブジェクトを使ってCREATE TABLEステートメントを実行し、OleDbParameterオブジェクトを使って列にパラメータを設定する必要がある。

下記は、2 列のテーブルを作成し、OleDbParameter を使用して列のデータ型と名前を定義する方法のサンプルコードです。

using System;
using System.Data;
using System.Data.OleDb;
class Program
{
static void Main()
{
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\your_database.mdb;";
string tableName = "YourTableName";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
// 创建一个命令对象
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = "CREATE TABLE " + tableName + " (ID INT, Name VARCHAR(255));";
// 执行命令
command.ExecuteNonQuery();
}
// 向表中插入数据
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO " + tableName + " (ID, Name) VALUES (@ID, @Name)";
// 创建参数并定义其类型和值
OleDbParameter parameterID = new OleDbParameter("@ID", OleDbType.Integer);
parameterID.Value = 1;
OleDbParameter parameterName = new OleDbParameter("@Name", OleDbType.VarChar);
parameterName.Value = "John";
// 添加参数到命令对象
command.Parameters.Add(parameterID);
command.Parameters.Add(parameterName);
// 执行插入命令
command.ExecuteNonQuery();
}
// 关闭连接
connection.Close();
}
}
}

接続文字列とテーブル名は、実際の状況に合わせて変更してください。また、リソースを確実に解放するにはusing構文を使用することを推奨しています。

bannerAds