2011-09-22 11 views
2

Visual Studio 2010을 사용하여 C#에서 프로그램을 작성하고 .sdf 파일에서 데이터를 검색 할 때 오류가 발생합니다.C# Ado.net, 오류 : "쿼리를 구문 분석하는 동안 오류가 발생했습니다."

//DataAccess.cs

using System; 
using System.Collections.Generic; 
using System.Collections; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Configuration; 
using System.Data; 
using System.Data.SqlClient; 
using System.Data.SqlServerCe; 
/// <summary> 
/// Demonstrates how to work with SqlConnection objects 
/// </summary> 

    namespace GameDAL 
    { 
     /// <summary> 
     /// Serve as main database layer. 
     /// </summary> 
     /// 

     public class DataAccess 
     { 
      SqlCeConnection conn = null; 
      SqlDataReader rdr = null; 
      // 3. Pass the connection to a command object 
      SqlCommand cmd = null; 
      string strConnection =null; 
      string dbfile =null; 
      string TABLE_NAME = "Statistics"; 
      string conString; 
      /// <summary> 
      /// Initialise connection and connection string 
      /// </summary> 
      public DataAccess() 
      { 
       InitConnection(); 
      } 

      public void InitConnection() 
      { 
       // Create a connection to the file Statistics.sdf in the program folder 
       MessageBox.Show("test new reflection"); 
       dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\Statistics.sdf"; 
       MessageBox.Show("test time new conn"); 

       conn = new SqlCeConnection("datasource=" + dbfile); 
       MessageBox.Show("test before opening"); 

       conn.Open(); 
       MessageBox.Show("test before new connectionstr"); 
       conString = Properties.Settings.Default.StatisticsConnectionString; 

       if (conn == null) 
        MessageBox.Show("warning connis null !!!!!"); 

      } 

      /// <summary> 
      /// Returns connection to database. 
      /// </summary> 
      /// <returns></returns> 
      public SqlCeConnection GetConnection() 
      { 
       return conn; 
      } 

      /// <summary> 
      ///      /// Write one row to database containing winner name ,winner score and, winner nr of cards. 
      /// </summary> 
      /// <param name="winnerName">Name of winner</param> 
      /// <param name="winnerScore">Score of winner</param> 
      /// <param name="winnerNrOfCards"></param> 
      public void WriteDataToDatabase(string winnerName, int winnerScore, int winnerNrOfCards) 
      { 

       // Retrieve the connection string from the settings file 


       // Open the connection using the connection string. 
       using (conn) 
       { 

        // Insert into the SqlCe table. ExecuteNonQuery is best for inserts. 
        using (System.Data.SqlServerCe.SqlCeCommand com = new System.Data.SqlServerCe.SqlCeCommand("INSERT INTO"+TABLE_NAME + "VALUES(@winnerName, @winnerScore, @winnerNrOfCards)", conn)) 
        { 
         com.Connection = conn; 
         com.Parameters.AddWithValue("@winnerName", winnerName); 
         com.Parameters.AddWithValue("@winnerScore", winnerScore); 
         com.Parameters.AddWithValue("@winnerNumberOfcards", winnerNrOfCards); 
         com.ExecuteNonQuery(); 
        } 
       } 
      } 

      /// <summary> 
      /// Read data from database. 
      /// Put data in array list with DataFromDatabase-instances, containing the stats for each game. 
      /// <returns>Returns arrayList with all data of database..</returns> 

      public List<DataFromDatabase> ReadAllDataFromDataBase() 
      { 
       string winnerName; 
       int winnerScore; 
       int winnerNrOfCards; 

       if (conn == null) 
        InitConnection(); 

       //System.Collections.ArrayList arrayListWithStatsFromDatabase= new System.Collections.ArrayList(); 
       List<DataFromDatabase> dataFromDatabaseList = new List<DataFromDatabase>(); 
       SqlCeCommand com = new SqlCeCommand("SELECT winnerName, winnerScore, winnerNumberOfCards FROM Statistics"); 
       MessageBox.Show("Now we inside ReadAllData and will be using conn"); 

       if (conn == null) 
        MessageBox.Show("warning connis null !!!!! before using CONN"); 
       else 
        MessageBox.Show("conn is " + conn); 
       using (conn) 
       { 
        // Read in all values in the table. 
        MessageBox.Show("conn OK.. comm is" + com); 

        //("SELECT * FROM"+ TABLE_NAME, conn);   
        using (com) 
        { 
         com.Connection = conn; 
         MessageBox.Show("Now we inside ReadAllData and will be using reader.."); 
         SqlCeDataReader reader = com.ExecuteReader(); 
         MessageBox.Show("Now we inside ReadAllData and..after exec reader reader.."); 
         //Add data from each row in table of database. 
         while (reader.Read()) 
         { 
          winnerName = reader.GetString(0); 
          winnerScore = reader.GetInt32(1); 
          winnerNrOfCards = reader.GetInt32(2); 
          dataFromDatabaseList.Add(new DataFromDatabase(winnerName, winnerScore, winnerNrOfCards)); 
         } 

        } //end of using 

       } //end of using 2 

       return dataFromDatabaseList; 
      } //end of methods 

     } //end of class 
    } //end of namespace.. 

// 데이터베이스 테이블 : Statistics.sdf

테이블 이름 : 통계 여기

데이터베이스에서 클래스 데이터 검색의 규정을 따르십시오 열 : winnerName, winnerScore, winnerNumberOfCards

버그는이 방법으로 발생합니다.

ReadAllDataFromDatabase() SqlCeDataReader를 실행할 때 reader = com.ExecuteReader();

오류 메시지 : '{'. 쿼리를 구문 분석하는 동안 오류가 발생했습니다 [토큰 줄 번호 = 1, 토큰 라인 오프셋 = 58, 오류 토큰 = 통계] "} '

Error report: 

    System.Windows.Markup.XamlParseException was unhandled 
     Message=Anropet av konstruktorn av typen BlackJack.MainWindow som matchar de angivna bindningsbegränsningarna utlöste ett undantag. radnummer 4 och radposition 76. 
     Source=PresentationFramework 
     LineNumber=4 
     LinePosition=76 
     StackTrace: 
      vid System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri) 
      vid System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) 
      vid System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri) 
      vid System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) 
      vid System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc) 
      vid System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties) 
      vid System.Windows.Application.DoStartup() 
      vid System.Windows.Application.<.ctor>b__1(Object unused) 
      vid System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
      vid MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) 
      vid System.Windows.Threading.DispatcherOperation.InvokeImpl() 
      vid System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) 
      vid System.Threading.ExecutionContext.runTryCode(Object userData) 
      vid System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) 
      vid System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) 
      vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 
      vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
      vid System.Windows.Threading.DispatcherOperation.Invoke() 
      vid System.Windows.Threading.Dispatcher.ProcessQueue() 
      vid System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
      vid MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
      vid MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 
      vid System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
      vid MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) 
      vid System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 
      vid MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 
      vid MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 
      vid System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 
      vid System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) 
      vid System.Windows.Application.RunDispatcher(Object ignore) 
      vid System.Windows.Application.RunInternal(Window window) 
      vid System.Windows.Application.Run(Window window) 
      vid System.Windows.Application.Run() 
      vid BlackJack.App.Main() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\obj\x86\Debug\App.g.cs:rad 0 
      vid System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
      vid System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
      vid System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel) 
      vid System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() 
      vid System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData) 
      vid System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext) 
      vid System.Activator.CreateInstance(ActivationContext activationContext) 
      vid Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() 
      vid System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
      vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 
      vid System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
      vid System.Threading.ThreadHelper.ThreadStart() 
     InnerException: System.Data.SqlServerCe.SqlCeException 
      Message=There was an error parsing the query. [ Token line number = 1,Token line offset = 58,Token in error = Statistics ] 
      Source=SQL Server Compact ADO.NET Data Provider 
      HResult=-2147217900 
      NativeError=25501 
      StackTrace: 
       vid System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan() 
       vid System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options) 
       vid System.Data.SqlServerCe.SqlCeCommand.ExecuteReader(CommandBehavior behavior) 
       vid System.Data.SqlServerCe.SqlCeCommand.ExecuteReader() 
       vid GameDAL.DataAccess.ReadAllDataFromDataBase() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\GameDAL\DataAccess.cs:rad 133 
       vid BlackJack.GameManager.ReadInDataFromDatabase() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\GameManager.cs:rad 660 
       vid BlackJack.MainWindow.ResetListANDGUIWithStatisticsAndReadInNewDataFromDatabase() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\MainWindow.xaml.cs:rad 94 
       vid BlackJack.MainWindow..ctor() i D:\Programmering\C-sharp Malmö Advancd\BlackJack3\BlackJack\BlackJack\MainWindow.xaml.cs:rad 71 
      InnerException: 

무엇인가 이 오류의 이유는 무엇입니까?

답변

2

Statistics은 예약어이므로 [] 표기로 이름을 string TABLE_NAME = "[Statistics]"으로 이스케이프합니다.

string TABLE_NAME = "Statistics"; 

"INSERT INTO"+TABLE_NAME + "VAL 

그 결합하고 당신이해야하는 것은 당신이
"INSERT INTOStatisticsVAL 

를 얻을 :

+0

감사합니다. 그게 문제를 해결했습니다! –

0

당신은이

"INSERT INTO "+TABLE_NAME + " VAL 

또는 (더 좋음; 공백이있는 키워드 및 이름 등) :

"INSERT INTO ["+TABLE_NAME + "] VAL 
+0

위의 버그를 일으키는 오류가 아닙니다. 하지만 버그를 찾아 주셔서 감사합니다 !! –

관련 문제