问题
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();
The problem is that I'm getting an exception when I call cmd.ExecuteScalar
.
The exception message reads,
{"There was an error parsing the query. [ Token line number = 1,Token line offset = 97,Token in error = SELECT ]"}
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.
Any help would be greatly appreciated.
回答1:
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
来源:https://stackoverflow.com/questions/21514341/error-parsing-the-query-while-getting-identity-from-sql-server-ce