2013-06-02 28 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