<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script> width="728" scrolling="no" height="15" frameborder="0" allowtransparency="true" hspace="0" vspace="0" marginheight="0" marginwidth="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-2823374497557651&dt=1188534631051&lmt=1188534630&prev_fmts=728x15_0ads_al&format=728x15&output=html&correlator=1188534630951&url=http%3A%2F%2Fwww.cppblog.com%2Fadaiye%2Farchive%2F2007%2F08%2F31%2F31284.html&ref=http%3A%2F%2Fwww.cppblog.com%2Fadaiye%2F&cc=100&ga_vid=731820495.1188534631&ga_sid=1188534631&ga_hid=612645000&flash=9&u_h=768&u_w=1024&u_ah=734&u_aw=1024&u_cd=32&u_tz=480&u_his=19&u_java=true&u_nplug=15&u_nmime=54" name="google_ads_frame">
首先定义数据源等:" ../../Food.mdb " ;
另外可以自己定义两个与数据库取得连接和关闭连接的函数:
{
OleDbConnection newConnection = new OleDbConnection(strContent);
return newConnection;
}
public static void closeConnection(OleDbConnection conn)
{
if (conn != null )
{
conn.Close();
}
}
现在我们可以定义具体的数据库操作函数了。
如果是不用从数据库中取出数据的,而只是把数据存入数据库中,由于在很大程度上有很大一部分代码是重复使用的,所以,我选择定义另一个数据库操作函数exeNonQuerySQL(string strCommand):
{
conn = DBAccess.getConnection();
if (conn != null )
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(strCommand, conn);
cmd.ExecuteNonQuery();
return true ;
}
catch (Exception e)
{
return false ;
}
finally
{
conn.Close();
}
}
else
{
return false ;
}
}
{
string strCommand = " delete from menu where dishName = ' " + name + " ' " ;
return exeNonQuerySQL(strCommand);
}
另外,如果涉及到,从数据库中取出数据,则可以这样子:
{
Dish dish = null ;
string strCommand = " select comboID, dishName, price from menu where menu.dishName = ' " + str + " ' " ;
conn = DBAccess.getConnection();
if (conn != null )
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(strCommand, conn);
OleDbDataReader reader;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
dish = new Dish();
reader.Read();
dish.Id = Int32.Parse(reader[ " comboID " ].ToString());
dish.Name = reader[ " dishName " ].ToString();
dish.Price = Decimal.Parse(reader[ " price " ].ToString());
}
} catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
DBAccess.closeConnection(conn);
}
}
以上是我个人愚见! 大家多多指正!