問題: C# の Oledb インターフェイスを使用して、アクセス データベースに日時を挿入しようとしています。
ハッキングの解決策: command.Properties を使用せずに挿入文字列を生成する
問題なくテキストをデータベースに挿入できますが、datetime を試行すると、最終的に次のエラーが発生します: System.Data.OleDb.OleDbException {"Data type mismatch in criteria expression."}
これに似た投稿がいくつかありますが、残念ながら有効な解決策はありません。
これが私のコードです:
void TransferData()
{
string instCmd = Get_InsertCommand(0); // hard coded table 0 for testing
Fill_ProductTable_ToInsert();
con.Open();
// It would be nice not to have to separate the date indexes
int[] textIndex = { 0, 1, 2, 3, 4, 7 };
int[] dateIndex = { 5, 6 };
try
{
foreach (DataRow row in DataToStore.Tables[0].Rows)
{
OleDbCommand command = new OleDbCommand();
command.Connection = con;
command.CommandText = instCmd;
foreach(int j in textIndex)
command.Parameters.AddWithValue("@" + j, row[j]);
foreach (int j in dateIndex)
{
// TESTING CODE
///////////////////////////////////////////////////////////////////////////
string input = "#\'" +DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") +"\'#";
command.Parameters.AddWithValue("@" + j, input.ToString());
Program.WriteLine(input.ToString());
///////////////////////////////////////////////////////////////////////////
}
command.ExecuteNonQuery();
}
}
finally
{
con.Close();
}
}
string Get_InsertCommand(int i)
{
string sqlIns = "INSERT INTO " + DataToStore.Tables[0].TableName + " (";
string temp = "VALUES (";
for (int j = 0; j < expected_header[i].Length - 1; j++)
{
sqlIns += expected_header[i][j] + ", ";
temp += "@" + j + ", ";
}
int lastIndex = expected_header[i].Length -1;
sqlIns += expected_header[i][lastIndex] + ") ";
temp += "@" + lastIndex + ")";
sqlIns += temp;
return sqlIns;
}
テストコードとラベル付けされた領域内で、考えられるすべての日時の順列を試しました。# と ' を使用してすべての形式を試しました。これらの形式を試しました: yyyy-MM-dd、yyyyMMdd、yyyy\MM\dd、yyyy/MM/dd ToOADate() と ToString()、ToShortDateString() も試しました
ANSI-92 Sqlを受け入れるようにデータベースを設定しようとしました
私はアイデアが不足しています。
注: このコードは、複数のデータベースの複数のテーブルを処理するように設定されています。ループに注意してください...