【问题标题】:Cannot get data from Access database after making successful connection using WPF使用 WPF 成功连接后无法从 Access 数据库获取数据
【发布时间】:2016-10-14 13:58:36
【问题描述】:

我正在使用 WPF 项目编写 C# 代码。我有一个 ComboBox1 下拉列表,用户从我计算机上的 Microsoft Access 数据库中选择一个项目。在用户选择某些内容后,我想从用户刚刚选择进入文本块的同一行中检索某个值。

我收到 3 个相同的错误,并说“当前上下文中不存在名称 'connect'。”我不确定如何解决这个问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;

namespace bundlecalc
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MainWindow_Load();
        }

        private void MainWindow_Load()
        {   
            OleDbConnection connect = new OleDbConnection();
            connect.ConnectionString =  @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Projects\Database.accdb;
            Persist Security Info = False; ";
            connect.Open();

            OleDbCommand command = new OleDbCommand();
            command.Connection = connect;
            command.CommandText = "SELECT Column1 FROM Table1";

            OleDbDataReader reader = command.ExecuteReader();

            while(reader.Read())
            {
                ComboBox1.Items.Add(reader["Column1"].ToString());
            }
            connect.Close();

        }

        private void ComboBox1_SelectedIndexChanged(object sender, RoutedEventArgs e)
        {
            connect.Open();

            OleDbCommand command = new OleDbCommand();
            command.Connection = connect;
            string query = "select * from Table1 where Column1 ='" + ComboBox1.Text + "'";
            command.CommandText = query;

            OleDbDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                BetaAnswer.Text = reader["ValueFromRow"].ToString();
            }

            connect.Close();
        }
    }
}

【问题讨论】:

  • 声明连接为类成员
  • @viveknuna:坏主意。在长期存在的类中保留打开的连接对象只是在要求错误。

标签: c# wpf ms-access combobox


【解决方案1】:

MainWindow_Load 中声明connect 变量:

OleDbConnection connect = new OleDbConnection();

但是在ComboBox1_SelectedIndexChanged 你没有。也只需在该方法中声明它。

您还可以查看using 块中的一次性资源,例如数据库连接。比如:

using (OleDbConnection connect = new OleDbConnection())
{
    // use the connection
}

(您可能很想将connect 变量设置为可以被类中的所有内容重用的类级别成员。不要。这是一个众所周知的坏主意。数据库连接应该在很小的范围内被创建、使用和销毁。连接池为你处理重用。试图自己处理重用会导致问题。)

【讨论】:

  • 想补充一点,OP 不应使用连接的即席 sql 语句和用户界面控件。使用参数化查询或存储过程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 2013-04-13
  • 2018-10-29
  • 2017-08-12
  • 1970-01-01
相关资源
最近更新 更多