一开始,请允许我向StackOverFlow和所有用户表达我对所有人的敬意和敬意。你们帮我们这样的人做得很好。三江源。
现在我的问题: 我正在构建一个winforms应用程序,用于学习目的: 1)连接到数据库并根据查询检索结果。 2)查询由以下任一方式生成: *用户点击应用程序的各种控件或 *用户自己编写查询然后执行它。 3)结果显示在结果框上。
我收到的SQLException“附近的语法不正确”,“ 生成的语法是正确的,因为: 1)我复制了生成的查询并在SQL Management Studio中执行。它完美无缺地执行。 2)我尝试手动编写查询然后执行它但它仍然会抛出相同的执行。
请注意,在应用程序开发的第一阶段,它只有三个控件,一个DataGridView控件,一个TextBox控件和一个Button控件。在那个阶段,我成功地生成了结果并显示出来。 在我添加额外功能后,应用程序停止工作。我不明白为什么。我使用的是在开发的第一阶段使用的相同代码,实际上它是相同的应用程序。因此,我使用前面提到的三个基本控件创建了另一个应用程序,并复制了主要应用程序生成的查询,然后在第二个应用程序中执行它。它在那里工作。
在当前阶段,如果我使用生成的查询或者我自己编写查询然后执行它,应用程序将抛出相同的execption。 这是我的代码。当用户单击“执行”按钮时,将调用LoadData方法。
try
{
string ConnectString = "Data Source=(local); Initial Catalog=AdventureWorks2008;User ID=; Password=;Integrated Security=SSPI";
ConnectionObj.ConnectionString = ConnectString;//ConnectionObj is SQLConnection object defined in the same class as Loaddata()
ConnectionObj.Open();
ColumnNames = string.Empty;//ColumnNames is a String type defined in the same class as Loaddata()
foreach (string Name in ColumnNamesCheckedListBox.CheckedItems)//ColumnNamesCheckedListBox is a CheckedListBox control which lets user select ColumnNames from the corresponding table
{
ColumnNames = ColumnNames + Name + ", ";
}
int Length = ColumnNames.Length;
Length = Length - 2;//To remove the extra "," and "<space>" at the end of ColumnNames
string TempQuery = ColumnNames.Remove(length);
//User may use the query formed by the application or she may write her own query, hence using "string PossibleQuery"
//SelectQueryDropDownList is a ComboBox control holding the items "Select" "Update" "Insert" and "Delete". Used to generate the DML clause in the query
//Database_TreeView is a TreeView control that holds all the table names in the database. This is used to generate the "FROM" clause in the query
//QueryBox is a TextBox control that displays the generated query and if required lets the user write her own query manually
string PossibleQuery = SelectQueryDropDownList.SelectedItem.ToString() + TempQuery + " From " + Database_TreeView.SelectedNode.Name.ToString();
QueryBox.TempQuery = PossibleQuery;
string FinalQuery = QueryBox.Text; //incase the user modified the query at QueryBox manually
SqlDataAdapter DA = new SqlDataAdapter(FinalQuery, ConnectString);
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder(DA);
DataTable Table = new System.Data.DataTable();
//EXCEPTION OCCURS AT THIS STATEMENT
DA.Fill(Table);
BindingSource Source = new BindingSource();
Source.DataSource = Table;
ResultBox.DataSource = Source;//ResultBox is a DataGridView control to display the results of the the query after execution (if any)
}
catch (Exception e)
{
MessageBox.Show(e.Message+"\nPlease try again","Error",MessageBoxButtons.OK);
}
finally
{
ConnectionObj.Close();
}
以下是截图: 这是我的应用程序生成的查询。 http://i60.photobucket.com/albums/h31/spiderclaws/Stack%20Over%20Flow/1ScreenShot2013-04-23at54453PM.png
请帮帮我。感谢名单。 问候, Gogol Prasad (Spiderclaws@gmail.com) P.S.-请原谅我写这么长的帖子。我想让每个人都清楚。
[编辑] 这是所要求的信息: 请注意我正在查询 Person.BusinessEntityContact按截图...
FinalQuery=Select BusinessEntityID, PersonID, ContactTypeID From Person.BusinessEntityContact
StackTrace info:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior)
at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable)
at ADOBasicsWinFormsApp.Form1.loaddata() in C:\Users\Gogol\Documents\Visual Studio 2010\Projects\ADOBasicsConsoleApp\ADOBasicsWinFormsApp\Form1.cs:line 684
答案 0 :(得分:2)
查看您的图像似乎SELECT和第一个字段之间缺少空格
所以在SelectedItem和TempQuery之间添加一个空格
string PossibleQuery = SelectQueryDropDownList.SelectedItem.ToString() + " " +
TempQuery + " From " + Database_TreeView.SelectedNode.Name.ToString();
(我假设SelectQueryDropDownList包含单词SELECT)
除此之外,我建议使用StringBuilder来构建列名
StringBuilder cols = new StringBuilder()
// A check here is required to avoid empty selections
foreach (string Name in ColumnNamesCheckedListBox.CheckedItems)
cols.Append(Name + ",");
if(cols.Length > 0) cols.Length -= 2;
string TempQuery = cols.ToString();
此方法开始时创建的SqlConnection对象也不会传递到您的DataAdapter,也不会在其他地方使用,SqlDataAdapter会接收您的连接字符串,因此它会自行管理连接,这意味着它会打开连接并关闭连接。所以你可以删除它。
答案 1 :(得分:1)
这是
int length = ColumnNames.Length;
length = length - 2;
string TempQuery = ColumnNames.Remove(length);
将您的本地Length
变量更改为小写l
。
或者你可以重写它以摆脱局部变量:
string TempQuery = ColumnNames.Remove(ColumnNames.Length - 2);