为什么我得到一个未处理的例外"保存数据库条目时?

时间:2015-09-15 10:47:11

标签: c# dll

我目前正在开发一个数据库,可以跟踪停放在停车场的车辆。但是,我遇到了一些问题,将新记录保存到数据库表中。现在我仍然是一个相当新的程序,所以我无法理解我收到的错误。我试过查找并发现了类似情况,但情况并不完全相同。我在C#中创建了应用程序,我的数据库是一个访问.mdb文件。

我得到的当前错误如下:

"未处理的类型' System.InvalidOperationException'发生在System.Data.dll

附加信息:不允许更改' ConnectionString'属性。连接的当前状态是打开的"

我想指出,只有当我点击保存并且文本框中有值时才会发生这种情况。如果我点击保存而不输入任何内容,则表示"访客信息已成功保存"。

我对所发生的事情感到茫然,所以我希望这里有人可以提供帮助。到目前为止,我已经为Call app提供了代码。

以下是我的应用的代码:

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


namespace ParkingDatabase
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    OleDbConnection DBConnect = new OleDbConnection();
    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        DBConnect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\bkoso\Documents\Visual Studio 2015\Projects\ParkingDatabase\ParkingDatabase\ParkingData.mdb";
        DBConnect.Open();
        OleDbCommand com = new OleDbCommand("INSERT INTO Guest Info([Guest FName], [Guest LName], [Room #], Departure, Return, [Vehicle Colour], [Vehicle Make], [Plate #], [Contact FName], [Contact LName], [Contact #], [Contact Email], [Tag #]) Values(@[Guest FName], @[Guest LName], @[Room #], @Departure, @Return, @[Vehicle Colour], @[Vehicle Make], @[Plate #], @[Contact FName], @[Contact LName], @[Contact #], @[Contact Email], @[Tag #])", DBConnect);
            com.Parameters.AddWithValue("@[Guest FName]", txtBxGstFName.Text);
            com.Parameters.AddWithValue("@[Guest LName]", txtBxGstLName.Text);
            com.Parameters.AddWithValue("@[Room #]", txtBxRm.Text);
            com.Parameters.AddWithValue("@Departure", txtBxDDate.Text);
            com.Parameters.AddWithValue("@[Return]", txtBxRDate.Text);
            com.Parameters.AddWithValue("@[Vehicle Colour]", txtBxVColour.Text);
            com.Parameters.AddWithValue("@[Vehicle Make]", txtBxVMake.Text);
            com.Parameters.AddWithValue("@[Plate #]", txtBxPlate.Text);
            com.Parameters.AddWithValue("@[Contact FName]", txtBxContactFName.Text);
            com.Parameters.AddWithValue("@[Contact LName]", txtBxContactLName.Text);
            com.Parameters.AddWithValue("@[Contact #]", txtBxPhone.Text);
            com.Parameters.AddWithValue("@[Contact Email]", txtBxEmail.Text);
            com.Parameters.AddWithValue("@[Tag #", txtBxTag.Text);

        if (DBConnect.State == ConnectionState.Open)
        {
            try
            {
                //com.ExecuteNonQuery();
                MessageBox.Show("Guest Information Saved Successfully");
                txtBxGstFName.Text = "";
                txtBxGstLName.Text = "";
                txtBxRm.Text = "";
                txtBxDDate.Text = "";
                txtBxRDate.Text = "";
                txtBxVColour.Text = "";
                txtBxVMake.Text = "";
                txtBxPlate.Text = "";
                txtBxContactFName.Text = "";
                txtBxContactLName.Text = "";
                txtBxPhone.Text = "";
                txtBxEmail.Text = "";
                txtBxTag.Text = "";

            }
            catch (Exception notSaved)
            {
                if (DBConnect != null && DBConnect.State != ConnectionState.Closed)
                {
                    DBConnect.Close();
                }
                MessageBox.Show("Error Saving Data \n" + notSaved.ToString());
                DBConnect.Close();
            }
        }
        else
        {
            MessageBox.Show("Connection Failed");
        }
    }

    private void btnClear_Click(object sender, RoutedEventArgs e)
    {

    }

    private void btnView_Click(object sender, RoutedEventArgs e)
    {

    }

    private void btnSame_Click(object sender, RoutedEventArgs e)
    {

    }

    private void txtBoxGuestFirstName_TextChanged(object sender, TextChangedEventArgs e)
    {

    }


}
}

以下是调用堆栈:

>   ParkingDatabase.exe!ParkingDatabase.MainWindow.btnSave_Click(object sender, System.Windows.RoutedEventArgs e) Line 36   C#
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs e)  Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick()   Unknown
PresentationFramework.dll!System.Windows.Controls.Button.OnClick()  Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)    Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseLeftButtonUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)  Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent)  Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e)    Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target)   Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised)    Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args)   Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args)    Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input)  Unknown
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport)   Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel)   Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)   Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled)    Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs)  Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs)   Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam)  Unknown
[Native to Managed Transition]  
[Managed to Native Transition]  
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame)   Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame)   Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore)   Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window)  Unknown
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window)  Unknown
PresentationFramework.dll!System.Windows.Application.Run()  Unknown
ParkingDatabase.exe!ParkingDatabase.App.Main()  C#
[Native to Managed Transition]  
[Managed to Native Transition]  
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) Unknown
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()   Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state)    Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart()    Unknown

如果有人想知道调用堆栈中的未知是在语言列中。

在代码示例中,您可能会注意到第57行,com.ExecuteNonQuery(); ,被评论出来。原因是我的语法错误。

对此的任何帮助将不胜感激。如果我需要提供更多信息,请告诉我。

Bloodstalker

2 个答案:

答案 0 :(得分:1)

还有一个拼写错误:

这样:

com.Parameters.AddWithValue(“@ [Tag#”,txtBxTag.Text);

应该是:

com.Parameters.AddWithValue(“@ [Tag#]”,txtBxTag.Text);

答案 1 :(得分:0)

using语句会关闭您的连接。查看MSDN OleDbConnection案例(跳转到文章末尾的“示例”部分)。

您的代码应该是这样的:

private void btnSave_Click(object sender, RoutedEventArgs e)
{
    using (OleDbConnection DBConnect = new OleDbConnection())
    {
        DBConnect.ConnectionString = @"Provider=Mi...";
        DBConnect.Open();
        OleDbCommand com = new OleDbCommand("INSERT INTO ...", DBConnect);

        // Parameters goes here

        if (DBConnect.State == ConnectionState.Open)
        {
            com.ExecuteNonQuery();
        }

        //...

        // No need to close connection
    }
}