我需要创建一个MySQL表并在Mono中填充一些数据。我使用下面的代码可以这样做:我是否需要在MySQL中使用Transaction对象
public class TestModel
{
protected IDbConnection dbcon;
public TestModel()
{
string connectionString = "Server=localhost;"
+ "Database=cikdata;"
+ "User ID=root;"
+ "Password=password;"
+ "Pooling=false";
dbcon = new MySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
// Create table
dbcmd.CommandText = "CREATE TABLE employee (firstname varchar(32), lastname varchar(32))";
dbcmd.ExecuteScalar();
// fill this table with some data
dbcmd.CommandText = "SELECT firstname, lastname FROM employee";
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()) {
string FirstName = (string) reader["firstname"];
string LastName = (string) reader["lastname"];
Console.WriteLine("Name: " + FirstName + " " + LastName);
}
// clean up
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
}
~TestModel()
{
dbcon.Close();
dbcon = null;
}
}
我已经看到了如何使用MySQL在单在使用IDbTransaction
工作的例子很多。上面的代码没有任何事务对象。我真的需要在我的代码中使用交易对象(和IDbTransaction.Commit
)吗?
对不起,问这样一个新手问题。我主要是一名C++/PHP开发人员,而且我对C#和Mono很少有经验。
终结不好等 –
裹IDisposable的对象“使用”块,正如已经说过的,终结者在这里是一个糟糕的主意。 – skolima
谢谢@skolima。我已经意识到它为什么如此糟糕。另外,当'TestModel'对象还没有被删除时,我是否需要维护与数据库的持久连接?对于特定的数据库查询/事务,“打开”和“关闭”连接可能更好? – ezpresso