日期:2009-08-27  浏览次数:20458 次

public class operateDB
{


private static string conStr;

public static OleDbConnection cnn;
OleDbDataAdapter da;
OleDbCommandBuilder cb;
OleDbCommand cmd;

//构造函数
#region initialize
public operateDB()
{
//
// TODO: 在此处添加构造函数逻辑
//
cnn=new OleDbConnection();

da=new OleDbDataAdapter();
//不用OleDbCommand对象更新到数据库时,必须有下面一行
cb=new OleDbCommandBuilder(da);

cmd=new OleDbCommand();

}
#endregion initialize

//连接字符串
#region get&setConnectionString

/// <summary>
/// 获取连接字符串
/// </summary>
public string MyConStr
{
get {return conStr;}
set {conStr = value;}
}

#endregion get&setConnectionString

//获得表的名称
#region acquireTableNames

/// <summary>
/// 获取数据库中的表名集合
/// </summary>
/// <returns></returns>
public DataTable tablesCollection()
{
DataTable tbl=new DataTable();
try
{

cnn.ConnectionString=conStr;
cnn.Open();

tbl = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});

}
catch(Exception ce)
{
Console.WriteLine("产生错误:\n{0}",ce.Message);
}
finally
{
cnn.Close();
}
return tbl;
}

#endregion acquireTableNames

//填充数据
#region fillTable

/// <summary>
/// 填充dataTable的查询
/// </summary>
/// <param name="tblName">数据表(必须输入数据库中存在的名称,也可以是视图)</param>
/// <param name="sqlStr">SQL语句</param>
/// <returns>记录条数</returns>
public int select(DataTable tblName,string sqlStr)
{
int i=0;

// try
// {
//
tblName.Clear();
da.Dispose();

if (cnn.ConnectionString=="")
cnn.ConnectionString=conStr;
if (cnn.State!=ConnectionState.Open)
cnn.Open();
// OleDbCommand cmd=new OleDbCommand("select * from "+tblName.TableName+" where "+sqlStr,cnn);
cmd.Connection=cnn;
cmd.CommandType=CommandType.Text;
cmd.CommandText="select * from "+tblName.TableName+" where "+sqlStr;
da.SelectCommand=cmd;

i=da.Fill(tblName);
//
//
// }
// catch(Exception ce)
// {
// Console.WriteLine("产生错误:\n{0}",ce.Message);
// }
// finally
// {
//this.da.Dispose();
cnn.Close();

// }
return i;
}

#endregion fillTable

//插入记录
#region insert(use CommandBuilder)
/// <summary>
/// 插入记录(用OleDbCommandBuilder)
/// </summary>
/// <param name="tblName">数据表</param>
/// <param name="newRow">与表中字段对应的新行</param>
/// <returns>影响的行数</returns>
public int insert(DataTable tblName,DataRow newRow)
{
cnn.Open();
int i=0;

//
// try
// {
//如何判断OleDbDataAdapter是否已经Dispose

//下面如果不生成新的OleDbDataAdapter、OleDbCommandBuilder、OleDbCommand,
//而用原来的全局da,cb,cmd,则在一次操作中只能更新一张表
OleDbDataAdapter daIn=new OleDbDataAdapter();
OleDbCommandBuilder cbIn=new OleDbCommandBuilder(daIn);
OleDbC