转载C# Tutorials,ADO/adosample.cs
2024-07-21 02:25:35
供稿:网友
using system;
using system.data;
using system.data.ado;
public class mainclass
{
public static void main ()
{
// set access connection and select strings
string straccessconn = "provider=microsoft.jet.oledb.4.0;data source=bugtypes.mdb";
string straccessselect = "select * from categories";
//create the dataset and add the categories table to it
dataset mydataset = new dataset();
mydataset.tables.add("categories");
// create my access objects
adoconnection myaccessconn = new adoconnection(straccessconn);
adodatasetcommand myaccessdatasetcmd = new adodatasetcommand();
myaccessdatasetcmd.selectcommand = new adocommand(straccessselect,myaccessconn);
myaccessconn.open();
try
{
myaccessdatasetcmd.filldataset(mydataset,"categories");
}
finally
{
myaccessconn.close();
}
try
{
/* a dataset can contain multiple tables,
so let's get them all into an array */
datatable[] dta = mydataset.tables.all;
foreach (datatable dt in dta)
{
console.writeline("found data table {0}", dt.tablename);
}
/* the next two lines show two different ways
you can get the count of tables in a dataset */
console.writeline("{0} tables in data set", mydataset.tables.count);
console.writeline("{0} tables in data set", dta.length);
/* the next several lines show how to get information
on a specific table by name from the dataset */
console.writeline("{0} rows in categories table", mydataset.tables["categories"].rows.count);
/* the column info is automatically fetched from the
database, so we can read it here */
console.writeline("{0} columns in categories table", mydataset.tables["categories"].columns.count);
datacolumn[] drc = mydataset.tables["categories"].columns.all;
int i = 0;
foreach (datacolumn dc in drc)
{
/* print the column subscript, then the
column's name and its data type */
console.writeline("column name[{0}] is {1}, of type {2}",i++ , dc.columnname, dc.datatype);
}
datarow[] dra = mydataset.tables["categories"].rows.all;
foreach (datarow dr in dra)
{
/* print the categoryid as a subscript,
then the categoryname */
console.writeline("categoryname[{0}] is {1}", dr[0], dr[1]);
}
}
catch (exception e)
{
console.writeline("oooops. caught an exception:/n{0}", e.message);
}
}
}
本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。