我正在使用Visual Studio 2010在C#中编写程序,并在从.sdf文件中检索数据时出错。
此处遵循从数据库中检索数据的类的代码:
// 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
此方法中出现错误:
执行SqlCeDataReader时的ReadAllDataFromDatabase()= 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:
出现此错误的原因是什么?
答案 0 :(得分:2)
Statistics
是保留字,使用[]
表示法将其名称改为string TABLE_NAME = "[Statistics]"
。
答案 1 :(得分:0)
你有:
string TABLE_NAME = "Statistics";
和
"INSERT INTO"+TABLE_NAME + "VAL
结合这些,你得到
"INSERT INTOStatisticsVAL
你应该拥有的是:
"INSERT INTO "+TABLE_NAME + " VAL
或(更好;适用于关键字和带空格的名称等):
"INSERT INTO ["+TABLE_NAME + "] VAL