0

我的要求是从访问文件中读取日期列并使用一个值将其附加到文件名,以便使用 db 值创建具有日期时间戳的文件。

我正在尝试以下方法,但它给了我异常“行/列不存在数据”:

这是代码

        OleDbConnection conn = new OleDbConnection(connectionString);
        OleDbConnection conn1 = new OleDbConnection(connectionString);

        string dt  = "SELECT top 1 Date FROM Events";


        OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
        conn1.Open();
        OleDbDataReader rdr = cmd1.ExecuteReader();

        string time_stmp = rdr.GetInt32(0).ToString();

        rdr.Close();
        conn1.Close();

        string path = text_dir + "\\" + time_stmp + "_" + "BWC_Ejournal.txt";
4

2 回答 2

2

You'll need to call the Read() method on the OleDbDataReader object before accessing its data.

E.g.

OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = "";

if(rdr.Read())
{
    time_stmp = rdr.GetInt32(0).ToString();
}
else
{
    //handle no data situation here
}

This will also allow to handle a situation where no data is returned more gracefully too.

于 2013-06-07T11:31:42.620 回答
1

DATE是 ACE/Jet SQL 中的保留字。试试这个:

string dt  = "SELECT TOP 1 [Date] FROM Events";

编辑

在仔细查看您的代码时,我注意到您OleDbCommand在打开连接之前创建了对象。我也看到这会导致问题。FWIW,以下代码适用于我:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace oleDbTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var con = new OleDbConnection(
                        "Provider=Microsoft.ACE.OLEDB.12.0;" +
                        @"Data Source=C:\__tmp\main.accdb;"))
            {
                con.Open();
                using (var cmd = new OleDbCommand(
                            "SELECT TOP 1 [Date] FROM [Events]", con))
                {
                    string time_stmp =  Convert.ToDateTime(cmd.ExecuteScalar()).ToString("yyyyMMdd");
                    Console.WriteLine(time_stmp.ToString());
                }
                con.Close();
            }
            Console.WriteLine("Done.");
            System.Threading.Thread.Sleep(2000);
        }
    }
}
于 2013-06-07T11:04:54.690 回答