SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd = CreateParameterizedQuery();
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
DataTable tbl = new DataTable();
dap.Fill(tbl);
if (tbl.Rows.Count > 0)
{
grid.DataSource = tbl;
}
实际的 SQL 查询将在 SQL Management Studio 中产生结果。但是我得到 0 行数据。我在 tbl.Rows.Count 处设置了一个断点,我看到它是 0,并且单步执行将跳过设置 DataSource 的必要代码。
private SqlCommand CreateParameterizedQuery()
{
SqlCommand command = new SqlCommand();
string[] allTheseWords;
if (textBoxAllTheseWords.Text.Length > 0)
{
allTheseWords = textBoxAllTheseWords.Text.Split(' ');
string SQLQuery = "SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[id], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE ";
int i = 0;
foreach (string word in allTheseWords)
{
var name = "@word" + (i++).ToString();
command.Parameters.AddWithValue(name, "'%" + word + "%'");
SQLQuery = SQLQuery + String.Format(" [databaseName].[dbo].[reportTable].[fullreport] LIKE {0} AND ", name);
}
SQLQuery = SQLQuery + " [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]";
command.CommandText = SQLQuery;
}
return command;
}
我在 Windows 8 上使用带有 C# 的 WinForm。
SQLQuery 变量在调试时包含此数据
SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[customerID], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE [databaseName].[dbo].[reportTable].[fullreport] LIKE @word0 AND [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]
debugMySQL 是一种吐出带有替换参数的 SQL Query 的方法
public void debugMySQL()
{
string query = command.CommandText;
foreach (SqlParameter p in command.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
textBox1.Text = query;
}
输出看起来像
SELECT distinct [databaseName].[dbo].[customerTable].[name], [databaseName].[dbo].[customerTable].[dos], [databaseName].[dbo].[customerTable].[ACC], [databaseName].[dbo].[reportTable].[id], [databaseName].[dbo].[reportTable].[ACC], [databaseName].[dbo].[reportTable].[fullreport] FROM [databaseName].[dbo].[reportTable], [databaseName].[dbo].[customerTable] WHERE [databaseName].[dbo].[reportTable].[fullreport] LIKE '%single%' AND [databaseName].[dbo].[customerTable].[ACC] = [databaseName].[dbo].[reportTable].[ACC]