2013-06-02 38 views
0

我正在嘗試創建一個應用程序,用於創建一個跟蹤鍛鍊的數據庫文件。您按下標有「新建數據庫」的按鈕,並獲取「保存文件」對話框爲SQLite創建.db文件。表名來自WPF控件上的文本框到目前爲止,我已經完成了大部分工作......除了一行繼續測試我的耐心。整個代碼如下:System.Data.SQLite/ADO.NET-表格輸入格式不正確C#

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(); 
       }      
      } 
     } 
    } 

它說我在da.Update(table)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 

回答

0

你的問題是,在你的CREATE TABLE statment你宣佈dateInteger類型。然後稍後您將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錯誤的護理領域創建表。

+0

對我來說,這只是一個數據庫,實際上。我會照顧這個變化。 – nerdenator