"错误解析查询"同时获得从SQL Server CE @@标识标识、错误、QUOT、SQL

2023-09-03 07:45:45 作者:兮颜

我写在我使用本地SQL数据库(SQL Server CE)一个简单的桌面应用程序。这是有问题的部分:

I'm writing a simple desktop application in which I'm using a local SQL database (SQL Server CE). Here is the problematic section:

SqlCeConnection conn = new SqlCeConnection("Data Source=|DataDirectory|\\App_Data\\Rosters.sdf");
System.Data.SqlServerCe.SqlCeCommand cmd = new SqlCeCommand();
cmd.Connection = conn;

cmd.CommandText = String.Format("Insert into Teams (LeagueID, TeamName, Color) values ({0},'{1}','{2}');SELECT @@IDENTITY;", leagueID, txtTeamName.Text.Replace("'", "''"), txtColor.Text.Replace("'", "''"));
conn.Open();
int teamID = (int)cmd.ExecuteScalar();
conn.Close();

问题是,我发现了一个例外,当我打电话 cmd.ExecuteScalar

异常消息读取,

{有一个错误解析查询。[令牌行号=   1,令牌行偏移= 97,令牌错误= SELECT]} 的

{"There was an error parsing the query. [ Token line number = 1,Token line offset = 97,Token in error = SELECT ]"}

我已经通过直接查询运行在同一个数据库完全相同的命令,它运行良好 - 这让我觉得这个问题是不是与SQL Server CE

I have run the exact same command in the exact same database through a direct query, and it runs fine - which makes me think the problem is not with SQL Server CE.

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

推荐答案

SQL Server精简版仅支持每个命令一个语句,所以首先运行插入语句的ExecuteNonQuery,然后得到用的ExecuteScalar的身份,切记不要关闭在之间的连接

SQL Server Compact only supports a single statement per command, so first run the insert statement with executenonquery, then get the identity with executescalar, and remember not to close the connection in between