0

我正在尝试创建一个应用程序来创建一个跟踪锻炼的数据库文件。您按下一个标有“新建数据库”的按钮,然后打开“保存文件”对话框来为 SQLite 创建 .db 文件。表名来自 WPF 控件上的文本框 到目前为止,我已经完成了几乎所有工作......除了继续测试我耐心的一行。整个代码如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
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;

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


        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnNewDatabase_Click(object sender, RoutedEventArgs e)
        {
            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".db"; // Default file extension
            dlg.Filter = "SQLite3 Database File (.db)|*.db"; // Filter files by     extension 
            string dateTime = DateTime.Today.ToString("dd_mm_yyyy");
            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results 
            if (result == true)
            {
                // Save document 
                string filename = dlg.FileName;
                string cs = string.Format("URI=file:{0}", filename);
                string tableName = txtDataTableName.Text;
                using (SQLiteConnection con = new SQLiteConnection(cs))
                {
                    con.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(con))
                    {
                        cmd.CommandText = string.Format("CREATE TABLE {0}(date INTEGER PRIMARY KEY, machine TEXT NOT NULL, sets INTEGER NOT NULL, repetitions INTEGER NOT NULL, weight NOT NULL)", tableName);
                        Console.WriteLine(cmd.CommandText);
                        cmd.ExecuteNonQuery();
                    }

                    con.Close();
                }

                using (SQLiteConnection con = new SQLiteConnection(cs))
                {

                    DataTable table = new DataTable(tableName);

                    DataRow row;

                    table.Columns.Add("Date", System.Type.GetType("System.String"));

                    table.Columns.Add("Machine", System.Type.GetType("System.String"));

                    table.Columns.Add("Sets", System.Type.GetType("System.Int32"));

                    table.Columns.Add("Repetitions", System.Type.GetType("System.Int32"));

                    table.Columns.Add("Weight", System.Type.GetType("System.Int32"));

                    row = table.NewRow();
                    row["Date"] = dateTime;
                    row["Machine"] = "Seated Row";
                    row["Sets"] = 1;
                    row["Repetitions"] = 10;
                    row["Weight"] = 100;
                    table.Rows.Add(row);

                    string sql = String.Format("SELECT * FROM {0}", tableName);

                    using (SQLiteDataAdapter da = new SQLiteDataAdapter(sql, con)) 
                    {
                        using (new SQLiteCommandBuilder(da))
                        {
                            da.Fill(table);
                            da.Update(table);
                        }
                    }

                    con.Close();
                }                       
            }
        }
   }

这是说我的table论点da.Update(table)格式不正确。这是因为我date在数据库中的字段......它不喜欢我喂它的东西。如何正确格式化和键入date字段,以使数据适配器不会出错?

堆栈跟踪下面的伟大正义。

System.FormatException was unhandled
  HResult=-2146233033
  Message=Input string was not in a correct format.
  Source=System.Data
  StackTrace:
   at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs     rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
   at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
   at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
   at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
   at System.Data.Common.DbDataAdapter.Update(DataTable dataTable)
   at WorkoutDB1.MainWindow.btnNewDatabase_Click(Object sender, RoutedEventArgs e) in c:\Users\Aaron\SkyDrive\WorkoutDB2\WorkoutDB2\MainWindow.xaml.cs:line 96
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at WorkoutDB1.App.Main() in c:\Users\Aaron\SkyDrive\WorkoutDB2\WorkoutDB2\obj\Debug\App.g.cs:line 0
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException: null
4

1 回答 1

0

您的问题是,在您的CREATE TABLE声明中,您将该date列声明为 type Integer。然后稍后您将该date字段声明为String.

我不确定为什么要将日期声明为整数(或作为主键),尤其是因为对于每天锻炼不止一次的人来说,您似乎可以有很多重复项。

无论如何,解决方案:您需要将CHANGE TABLE命令更改为以下内容。

    using (SQLiteCommand cmd = new SQLiteCommand(con))
        {
            cmd.CommandText = string.Format("CREATE TABLE {0}(date TEXT PRIMARY KEY, machine TEXT NOT NULL, sets INTEGER NOT NULL, repetitions INTEGER NOT NULL, weight NOT NULL)", tableName);
            Console.WriteLine(cmd.CommandText);
            cmd.ExecuteNonQuery();
        }

这将创建具有接受类型输入的字段的表,string并将处理input string not in correct format错误。

于 2013-06-02T23:25:03.073 回答