DataTable未获取所请求的数据

时间:2013-02-01 16:42:24

标签: c# sql winforms datatable sqlcommand

我在SQL Server Management Studio中运行了SQL查询,但它运行良好。

我的WinForm C#应用程序中出现以下错误

The parameterized query '(@word1 text)SELECT distinct [database].[dbo].[tableName].[n' expects the parameter '@word1', which was not supplied.

这是我的代码

    private void buttonRunQuery_Click(object sender, EventArgs e)
     {
         if (connection == null)
         {
             connection = ConnectionStateToSQLServer();
             SqlCommand command = new SqlCommand(null, connection);
             command = createSQLQuery(command);
             GetData(command);
         }
         else
         {
             SqlCommand command = new SqlCommand(null, connection);
             command = createSQLQuery(command);
             GetData(command);
         }
     }

    private SqlCommand createSQLQuery(SqlCommand command)
     {
         string[] allTheseWords;
         if (textBoxAllTheseWords.Text.Length > 0)
         {
             allTheseWords = textBoxAllTheseWords.Text.Split(' ');
             string SQLQuery = "SELECT distinct [database].[dbo].[customerTable].[name], [database].[dbo].[customerTable].[dos], [database].[dbo].[customerTable].[accountID], [database].[dbo].[reportTable].[customerID], [database].[dbo].[reportTable].[accountID], [database].[dbo].[reportTable].[fullreport] FROM [database].[dbo].[reportTable], [database].[dbo].[customerTable] WHERE ";
             int i = 1;
             foreach (string word in allTheseWords)
             {
                 var name = "@word" + (i++).ToString();
                 command.Parameters.Add(name, SqlDbType.Text);
                     //(name, SqlDbType.Text).Value = word;
                 SQLQuery = SQLQuery + String.Format(" [database].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
             }
             SQLQuery = SQLQuery + " [database].[dbo].[customerTable].[accountID] = [database].[dbo].[reportTable].[accountID]";
             command.CommandText = SQLQuery;
         }
         MessageBox.Show(command.CommandText.ToString());
         return command;
     }

    public DataTable GetData(SqlCommand cmd)
     {
         //SqlConnection con = new SqlConnection(connString);
         //SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
         SqlDataAdapter da = new SqlDataAdapter(cmd);
         connection.Open();
         DataTable dt = new DataTable();
         da.Fill(dt);
         connection.Close();
         return dt;
     } 

错误发生在da.Fill(dt)

任何建议都会有所帮助

谢谢

2 个答案:

答案 0 :(得分:1)

On var name =“@ word”+(i ++)。ToString();只使用我,在其他地方增加。

答案 1 :(得分:1)

在您的示例中,您已注释掉设置参数值的行:

command.Parameters.Add(name, SqlDbType.Text);
//(name, SqlDbType.Text).Value = word;

如果没有为参数设置值,则会忽略它(并且不会存在)。 改为:

command.Parameters.AddWithValue(name, word);

为清楚起见,请考虑以下引用:

  

要添加的值。使用DBNull.Value而不是null来指示空值。

从这里开始:SqlParameterCollection.AddWithValue Method