我有一些代码在Access数据库中执行UPDATE
查询。有时候它有效,有时我会收到这个错误:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Cannot open database ''. It may not be a database that your application recognizes, or the file may be corrupt.
以下是代码:
string[] lines = File.ReadAllLines(file, Encoding.GetEncoding(1252)); //read as ANSI encoding
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\\myDatabase.accdb");
con.Open();
for (int i = 2; i < lines.Length - 1; i++) //ignore the first 2 lines
{
string line = lines[i]; //get the current line
string[] values = line.Split('\t'); //split line at the tabs
using (OleDbCommand com = new OleDbCommand("INSERT INTO [myTable](" +
"[Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], " +
"[Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1], [Field1]" +
"[Field1], [Field1], [Field1]" +
") VALUES (" +
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" +
")", con))
{
for (int y = 0; y < 23; y++)
{
if (values[y] != "")
{
com.Parameters.Add("@p" + y + "", OleDbType.Char, 255).Value = (object)values[y] ?? DBNull.Value;
}
else
{
com.Parameters.Add("@p" + y + "", OleDbType.Char, 255).Value = DBNull.Value;
}
}
com.ExecuteNonQuery();
}
}
con.Close();
知道造成这种情况的原因是什么?为什么它只在某些时候有效?我在运行代码时没有在Access中打开实际的.accdb文件。
谢谢!
编辑:在运行上面的代码之前,它运行此代码就好了:
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\\myDatabase.accdb");
con.Open();
string strCreate = "CREATE TABLE [myTable](" +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255), " +
"[Field1] Text(255))";
OleDbCommand cCom = new OleDbCommand(strCreate, con);
cCom.ExecuteNonQuery();
cCom.Connection.Close();
答案 0 :(得分:2)
你能抓住异常和内部异常吗?它应该对这个问题有所了解:
try
{
// Your Code Here
}
catch (OleDbException e)
{
Messagebox.Show(e.InnerException.Message);
}