我使用OleDbConnection连接到带有WPF的C#Visual Studio 2013的MS Access 2013数据库,并且我在我的连接类中使用了外观设计模式 -
public class Connection
{
private readonly OleDbConnection con;
private readonly string path;
private bool connected;
public Connection(string path)
{
connected = false;
this.path = path;
string conString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + path + ";";
this.con = new OleDbConnection(conString);
}
public string Path { get { return path; } }
public bool Connected { get { return connected; } }
public void Open()
{
this.con.Open();
connected = true;
}
public DataSet GetData(string sql) // get dataset of with data of this sql query
{
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, con);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
public T GetItem<T>(string sql) // get an single item
{
return (T) GetData(sql).Tables[0].Rows[0][0];
}
public void Execute(string sql) // execute Insert, Delete etc..
{
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = sql;
ocmd.Connection = con;
Execute(ocmd);
}
public void Execute(OleDbCommand cmd)
{
cmd.ExecuteNonQuery();
cmd.Dispose();
}
public void Close()
{
this.con.Close();
connected = false;
}
public override string ToString()
{
return "[Connection: Path=" + path + "Connected=" + connected + " ]";
}
}
GetData
方法有效。 Execute
方法似乎有效,但是当我查看数据库时它并没有改变任何东西,那么奇怪的是:
Connection db = new Connection("Database\\Database.accdb");
db.Open();
int count = db.GetItem<int>("SELECT COUNT(ScoreID) FROM tblScores");
Console.WriteLine(count); // prints 1
db.Execute("INSERT INTO tblScores VALUES (1, 'My Awsome Name', 'Easy', 3, Date())");
count = db.GetItem<int>("SELECT COUNT(ScoreID) FROM tblScores");
Console.WriteLine(count); // prints 2 (??)
db.Close();
运行后我查看数据库,但我看不到这行... 我尝试直接在访问时运行查询(打开MS Access 2013)并且它工作正常。当我尝试使用已经在其中的主键执行查询时抛出异常,那么这里有什么问题?
答案 0 :(得分:0)
public void Execute(string sql) // execute Insert, Delete etc..
{
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = sql;
ocmd.Connection = con;
Execute(ocmd);
}
public void Execute(OleDbCommand cmd)
{
try
{
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
问题可能出在你的INSERT语句中 - 在Access数据库中,Date必须用#符号包裹起来:
"INSERT INTO tblScores VALUES (1, 'My Awsome Name', 'Easy', 3, #" + DateTime.Now() + "#)"