數據層,包括對數據庫的所有操作.重組DataTable等
using System;
using System.Data;
using System.Data.SqlClIEnt;
using System.ComponentModel;
namespace train
...{
/**//// <summary>
/// 數據層操作類
/// </summary>
public class DataBaSEOperate
...{
private SqlConnection conn;
private TrainConfiguration config;
private string path;
public DataBaSEOperate()
...{
conn=new SqlConnection();
config=new TrainConfiguration();
path=Environment.CurrentDirectory+"\config\config.txt";
}
/**//// <summary>
/// 打開數據庫連接
/// </summary>
/// <returns>返回bool值,true表示連接成功,false表示連接失敗</returns>
public bool ConnectDataBase()
...{
try
...{
if(conn.State!=ConnectionState.Open)
...{
conn.ConnectionString=config.GetConfigFromFile(this.path);
conn.Open();
return true;
&nbs
p; }
else
...{
return true;
}
}
catch(SqlException e)
...{
Console.WriteLine(e.Message);
return false;
}
}
/**//// <summary>
/// 關閉數據庫連接
/// </summary>
/// <returns>返回bool值,true表示關閉成功,false表示關閉失敗</returns>
public bool CloseDataBase()
...{
try
...{
if(conn.State!=ConnectionState.Closed)
...{
conn.Close();
}
return true;
}
catch(SqlException)
...{
return false;
}
}
/**//// <summary>
/// 根據sql語句執行數據庫查詢
/// </summary>
/// <param name="querysql">要執行的sql語句</param>
/// <returns>返回一個DataTable集合</returns>
public DataTable search(string querysql)
...{
if(conn.State!=ConnectionState.Open)
...{
ConnectDataBase();
}
ConnectDataBase();
SqlCommand cmd=new SqlCommand(querysql,conn);
SqlDataReader dr=null;
try
...{
dr=cmd.ExecuteReader();
}
catch(SqlException e)
...{
Console.WriteLine(e.Message);
return null;
}
//根據DataReader重組一個DataTable
DataTable table=new DataTable();
int colum=dr.FIEldCount;
table.BeginLoadData();
for(int i=0;i<colum;i++)
...{
table.Columns.Add(dr.GetName(i),dr.GetType());
}
object[] values=new object[colum];
while(dr.Read())
...{
DataRow row=table.NewRow();
dr.GetValues(values);
for(int i=0;i<values.Length;i++)
...{
row[i]=values[i];
}
table.Rows.Add(row);
}
table.EndLoadData();
dr.Close();
return table;
}
}
}