OleDbconnection conn=new OleDbconnection("str");對於OleDbconnection類,我們通過它和sql語句對數據庫文件連接。
例子:
string str1 = Application.StartupPath;//定位運行的程序所在的文件目錄
string str = "provider=Microsoft.Jet.OLEDB.4.0; data Source="+str1+@"\telephone.mdb; Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(str);
這樣我們就可以通過conn對象來獲取數據庫信息了。
datacommand類,我們通過datacommand數據庫命令對象對數據庫的信息進行sql語句操作。
例子:
string str="provider=Microsoft.Jet.OLEDB.4.0; data Source=D:/Student.mdb; Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(str);
string SQLstr = "insert into StudentInfo values(6,'09015','張川','軟件工程','軟件092班','江蘇','0')";
OleDbCommand comm = new OleDbCommand(SQLstr, conn);
try
{
conn.Open();
int i = comm.ExecuteNonQuery();//command的方法-返回被印象的行數
Console.WriteLine(i.ToString() + " rows affected by insert");
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
在這個例子中我們通過OleDbconection連接數據庫,在同command對數據庫插入新的元素。在此強調:我們進行數據庫conn.open()時需要做異常處理一檢查數據庫連接時的異常。
dataset對象:當使用了conn.open()方法時我們將會一直連接之數據庫對象直至close()。但是有時我們並不想一直打開數據庫對象(這樣很不安全),這事我們將會使用dataset對象,次對象通過adapter對象對數據庫中的信息全部複製-生成一個與源數據庫中的表一樣的表信息常駐內存。
例子:
public DataSet bandsource()
{
string str1 = Application.StartupPath;
string str = "provider=Microsoft.Jet.OLEDB.4.0; data Source="+str1+@"\telephone.mdb; Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(str);
ds = new DataSet();
try
{
conn.Open();
string sqlstr = "select telephoneinfo.PersonID,telephoneinfo.Name,telephoneinfo.Sex,telephoneinfo.OfficeTel,telephoneinfo.HomeTel,telephoneinfo.Mark from telephoneinfo order by PersonID";
da = new OleDbDataAdapter(sqlstr, conn);
da.Fill(ds, "phone");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
conn.Close();
}
n = ds.Tables[0].Rows.Count;
return ds;
}
這事一個綁定方法,我們通過dataadapter的方法fill()將數據庫中的信息放置到dataset中。
datareader對象:
DataReader對象是從一個數據源中選擇某些數據的最簡單方法,尤其適合讀取大量的數據,因爲它不在內存中緩存。
例子:
public static void Main()
{
string str = "provider=Microsoft.Jet.OLEDB.4.0; data Source=D:/Student.mdb; Persist Security Info=False";
OleDbConnection conn = new OleDbConnection(str);
string SQLstr = "select top 2 * from StudentINfo";
OleDbCommand comm = new OleDbCommand(SQLstr, conn);
OleDbDataReader rd;
try{
conn.Open();
rd = comm.ExecuteReader();
while (rd.Read())
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
rd[“StudentID”].ToString(),rd[“XueHao”],//用字符串引用字段
rd[2],rd[3],rd[4],rd[5]); // 用數字序號引用字段 }
rd.Close();}
catch (Exception ex)
{
Console.WriteLine(ex.Message); }
finally
{
conn.Close();}
}
這裏我們使用datareader對象接收command對象返回的數據。