首页 > 解决方案 > 没有为一个或多个必需参数提供值 - C#/Access

问题描述

这是我第一次尝试读取 Access 数据库并将每一行写入控制台。当我执行应用程序时,我在以下语句中抛出一个异常,上面写着“没有为一个或多个必需参数提供值”:

OleDbDataReader 阅读器 = cmd.ExecuteReader();

我对 c# 编程比较陌生,经过数小时的研究,我无法弄清楚我做错了什么。这是我的代码:

private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //Use a variable to hold the SQL statement.
        string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";

        try
        {
            //Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
            OleDbCommand cmd = new OleDbCommand(inputString, conn);

            //Send the CommandText to the connection, and then build an OleDbDataReader.
            OleDbDataReader reader = cmd.ExecuteReader();

            while (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
                    reader.NextResult();
                }
            }
            reader.Close();
        }
        catch (Exception ex)
        {
            error_message = ex.Message;
            MessageBox.Show(error_message);
        }

作为对评论者的回应,我发布了一段更大的代码来消除任何假设,并更好地了解我正在尝试做的事情:

using System;
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;
using System.IO;

namespace AzFloodSquad
{
    public partial class frm1DefaultScreen : Form
    {
        //Initialize the application
        String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
        OleDbConnection conn = null;
        String error_message = "";
        String q = "";
        string varReportId = "";

    public frm1DefaultScreen()
    {
        InitializeComponent();
    }

    //Load the default form
    private void frm1DefaultScreen_Load(object sender, EventArgs e)
    {
        connectToolStripMenuItem.PerformClick();
        contactsToolStripMenuItem.PerformClick();
    }

    //Exit the application
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    //Start the database
    private void connectToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            conn = new OleDbConnection(conn_string);
            conn.Open();
            disconnectToolStripMenuItem.Enabled = true;
            connectToolStripMenuItem.Enabled = false;
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

    //Stop the database
    private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            conn.Close();
            disconnectToolStripMenuItem.Enabled = false;
            connectToolStripMenuItem.Enabled = true;
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

    //Clean up database whem form close button clicked
    private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
    {
        disconnectToolStripMenuItem.PerformClick();
    }

    private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        varReportId = "Contacts";
        q = "SELECT * " +
                "FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
                    "OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
                    "OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
                        "ORDER BY FULL_NAME";

        this.Cursor = Cursors.WaitCursor;
        run_Query_Parm(q);
        this.Cursor = Cursors.Default;
    }

    //Pull data from the database using the parameter field
    private void run_Query_Parm(String q)
    {
        error_message = "";
        try
        {
            OleDbCommand cmd = new OleDbCommand(q, conn);
            OleDbDataAdapter a = new OleDbDataAdapter(cmd);

            DataTable dt = new DataTable();

            a.SelectCommand = cmd;
            a.Fill(dt);

            results.DataSource = dt;
            results.AutoResizeColumns();
        }
        catch (Exception ex)
        {
            error_message = ex.Message;
            MessageBox.Show(error_message);
        }
    }

    //Clear all data from the screen
    private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
    {
        varReportId = "";
        if (this.results.DataSource != null)
        {
            this.results.DataSource = null;
        }
        else
        {
            this.results.Rows.Clear();
        }
    }

    private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //Use a variable to hold the SQL statement.
        string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";

        try
        {
            //Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
            OleDbCommand cmd = new OleDbCommand(inputString, conn);

            //Send the CommandText to the connection, and then build an OleDbDataReader.
            OleDbDataReader reader = cmd.ExecuteReader();

            while (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
                    reader.NextResult();
                }

            }
            reader.Close();
        }
        catch (Exception ex)
        {
            error_message = ex.Message;
            MessageBox.Show(error_message);
        }
    }

提供的任何帮助将不胜感激。提前致谢。

标签: c#ms-access

解决方案


我发现了问题。显然,我的 SELECT 语句语法不正确。当我用以下代码替换我的 SELECT (显示在我发布的第一个代码示例中)时,它运行良好:

string inputString = "SELECT Contacts.[Account_Number], " +
            "Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
            "Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";

推荐阅读