本文介绍了Oledbdatareader reader = comand.executereader();这一行出错了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

namespace practice2
{
    public partial class Form1 : Form
    {
       private OleDbConnection connection = new OleDbConnection();
       
        public Form1()
        {
            InitializeComponent();
             connection.ConnectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Ahmed ch\Documents\Database1.accdb;
            Persist Security Info = False;";
           
        }

      
        private void Form1_Load(object sender, EventArgs e)
        {
           try
            {
            connection.Open();
           
                OleDbCommand comand = new OleDbCommand();
                String query =  "select* from Sheet2"
                comand.CommandText = query;
                OleDbDataReader reader = comand.ExecuteReader();
                while (reader.Read())
                {
                     comboBox1.Items.Add(reader["ProductName"].ToString());
                }


                connection.Close();
               
            }
                catch(Exception ex)
            {
                MessageBox.Show("Error" + ex);
                
            }
           
       
        }}}





我尝试过:



i还安装oledb驱动程序,MS Access数据库引擎X86,也是X64,但每次出现错误,



What I have tried:

i also install oledb driver , MS Access database Engine X86 , also X64 , but every time error comes ,

OleDbDataReader reader = comand.ExecuteReader();

在这一行

推荐答案

private void Form1_Load(object sender, EventArgs e)
{
  try
  {
    connection.Open();

    OleDbCommand comand = new OleDbCommand();
    String query = "select* from Sheet2"
    comand.CommandText = query;
    comand.Connection = connection;  // <<<< set connection
    OleDbDataReader reader = comand.ExecuteReader();
  // ....
}


try
    {
    using (OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\Ahmed ch\Documents\Database1.accdb;Persist Security Info = False;";))
        {
        con.Open();
        using (OleDbCommand cmd = new OleDbCommand("SELECT ProductName FROM Sheet2", con))
            {
            using (OleDbDataReader reader = cmd.ExecuteReader())
                {
                while (reader.Read())
                    {
                    comboBox1.Items.Add(reader["ProductName"].ToString());
                    }
                }
            }
        }
    }
catch(Exception ex)
    {
    MessageBox.Show("Error" + ex);
    }


这篇关于Oledbdatareader reader = comand.executereader();这一行出错了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 18:49