将平面MDB转换为SQL链接的MDB后,代码不再用于计算记录

时间:2011-05-12 20:56:01

标签: c# ms-access odbc

我使用了来自technet的这个示例代码来计算MDB文件中的记录。将访问数据库中的表转换为链接到SQL(使用ODBC)后,该程序不再有效。是否有一种简单的方法来修改此代码,以便它仍然可以通过查询MDB文件获取记录计数?

奇怪的是,您可以打开MDB文件并正常查看数据,它只是从SQL中提取数据。为什么这个代码在查询mdb时不能这样做?

using System;
using System.Data;
using System.Data.OleDb;
using System.Xml.Serialization;

public class MainClass {
    public static void Main ()
    {
        string strAccessConn = 
                    "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=BugTypes.MDB";
        string strAccessSelect = "SELECT * FROM Categories";
        DataSet myDataSet = new DataSet();
        OleDbConnection myAccessConn = null;
        try
        {
            myAccessConn = new OleDbConnection(strAccessConn);
        }
        catch(Exception ex)
        {
            Console.WriteLine(
                "Error: Failed to create a database connection. \n{0}", 
                ex.Message);
            return;
        }

        try
        {                
            OleDbCommand myAccessCommand = 
                                new OleDbCommand(strAccessSelect,myAccessConn);
            OleDbDataAdapter myDataAdapter = 
                                new OleDbDataAdapter(myAccessCommand);

            myAccessConn.Open();
            myDataAdapter.Fill(myDataSet,"Categories");

        }
        catch (Exception ex)
        {
            Console.WriteLine(
              "Error: Failed to retrieve the required data from the DataBase.\n{0}",
              ex.Message);
            return;
        }
        finally
        {
            myAccessConn.Close();
        }
        DataTableCollection dta = myDataSet.Tables;
        foreach (DataTable dt in dta)
        {
            Console.WriteLine("Found data table {0}", dt.TableName);
        }
        Console.WriteLine("{0} tables in data set", myDataSet.Tables.Count);
        Console.WriteLine("{0} tables in data set", dta.Count);
        Console.WriteLine("{0} rows in Categories table",
                            myDataSet.Tables["Categories"].Rows.Count);
        Console.WriteLine("{0} columns in Categories table",
                            myDataSet.Tables["Categories"].Columns.Count);
        DataColumnCollection drc = myDataSet.Tables["Categories"].Columns;
        int i = 0;
        foreach (DataColumn dc in drc)
        {
            Console.WriteLine("Column name[{0}] is {1}, of type {2}", i++,
                                dc.ColumnName, dc.DataType);
        }
        DataRowCollection dra = myDataSet.Tables["Categories"].Rows;
        foreach (DataRow dr in dra)
        {
            Console.WriteLine("CategoryName[{0}] is {1}", dr[0], dr[1]);
        }          
    }
}

此处的代码:http://msdn.microsoft.com/en-us/library/aa288452(v=vs.71).aspx

2 个答案:

答案 0 :(得分:1)

做一个

会不会更容易
Select count('x') as rowCount from categories

然后从数据集中的第一个(也是唯一的)记录中提取rowCount

答案 1 :(得分:0)

你说它不再起作用,并暗示这是一个有问题的问题,但哪一部分不起作用?

Rows.Count是否为0,但数据表中的行是否存在?或者数据集中没有表格或什么?