Windows窗体应用程序中的SQLException

本文关键字:SQLException 应用程序 窗体 Windows | 更新日期: 2023-09-27 18:10:35

首先请允许我向StackOverFlow的每个人以及所有用户表达我的问候和敬意。你们在帮助像我们这样的人方面做得很好。谢谢。

现在我的问题:我正在建立一个winforms应用程序,用于学习目的,即:1)连接到数据库并根据查询检索结果。2)查询由以下任意一种生成:*用户点击应用程序的各种控件或*用户自己编写查询,然后执行。3)结果显示在结果框中。

我得到一个SQLException "不正确的语法附近',' "生成的语法是正确的,因为:1)我复制了生成的查询,并在SQL管理工作室执行。它在那里执行得完美无缺。2)我尝试手动编写查询,然后执行它,但它仍然抛出相同的异常。

请注意,在应用程序开发的第一阶段,它只有三个控件,一个DataGridView控件,一个TextBox控件和一个Button控件。在这个阶段,我成功地生成了结果并显示了它们。在我添加了额外的功能后,应用程序停止工作了。我不明白为什么。我使用相同的代码,我在开发的第一阶段使用,事实上它是相同的应用程序。因此,我使用前面提到的三个基本控件创建了另一个应用程序,并复制了主应用程序生成的查询,然后在第二个应用程序中执行它。

在当前阶段,如果我使用生成的查询或如果我自己编写查询然后执行它,应用程序都会抛出相同的异常。这是我的代码。当用户点击"Execute"按钮时,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

显示生成的异常。http://i60.photobucket.com/albums/h31/spiderclaws/Stack%20Over%20Flow/2ScreenShot2013-04-23at54550PM.png

请帮帮我。谢谢。问候,果戈理普拉萨德(Spiderclaws@gmail.com)附言——请原谅我写了这么长的一篇文章。我想让每个人都明白。

[编辑]以下是所要求的信息:请注意我是在查询的人。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

Windows窗体应用程序中的SQLException

查看您的图像,似乎在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接收您的connectionstring,因此它自己管理连接,这意味着它打开连接并关闭连接。所以你可以删除它

在这里

int length = ColumnNames.Length;
length = length - 2;
string TempQuery = ColumnNames.Remove(length);

将本地的Length变量改为小写的l

或者您可以重写它以摆脱局部变量:

string TempQuery = ColumnNames.Remove(ColumnNames.Length - 2);