0

ワークアウトを追跡するデータベース ファイルを作成するアプリケーションを作成しようとしています。「新しいデータベース」というラベルの付いたボタンを押すと、ファイルの保存ダイアログが表示され、SQLite の .db ファイルが作成されます。テーブル名は、WPF コントロールのテキスト ボックスからのものです。これまでのところ、ほぼすべての作業が完了しています... 1 行を除いて、引き続き忍耐力が試されます。コード全体は次のとおりです。

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

問題は、ステートメントで列を type としてCREATE TABLE宣言したことです。その後、フィールドを として宣言します。dateIntegerdateString

日付を整数 (または主キー) として宣言する理由が正確にはわかりません。

とにかく、解決策に進みます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();
        }

これにより、タイプの入力を受け入れstringinput string not in correct formatエラーを処理するフィールドを持つテーブルが作成されます。

于 2013-06-02T23:25:03.073 に答える