【发布时间】:2013-07-18 16:58:07
【问题描述】:
这段代码只能从 0 循环到 3。当我将变量 i 增加到 4 或更多时,它不会带来结果。我有将近 700 条描述要查询。我怎样才能做到这一点?这是我的代码。谢谢,
SqlCommandBuilder myBuilder;
DataSet mySet;
DataTable myTable;
SqlDataReader myReader = null;
SqlCommand myCommand = null;
private void button1_Click(object sender, EventArgs e)
{
String str = "";
int specRowCount = dataGridView2.Rows.Count;
mySet = new DataSet();
try
{
myConnection.Open();
for (int i = 0; i <= 3; i++)
{
str = "use " + textBox4.Text + " SELECT * FROM myTable where myRule=1 and myFlag=1 and description='" + dataGridView2.Rows[i].Cells[0].Value.ToString() + "'";
//myCommand = new SqlCommand(str, myConnection);
myAdapter = new SqlDataAdapter(str, myConnection);
//myBuilder = new SqlCommandBuilder(myAdapter);
myAdapter.Fill(mySet, "t_rules");
}
myTable = mySet.Tables["t_rules"];
myConnection.Close();
dataGridView1.DataSource = mySet.Tables["t_rules"];
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
【问题讨论】:
-
您的代码容易受到 SQL 注入攻击,我会先解决这个问题。
-
附带说明,这显然不是控制台应用程序,但问题是写入控制台。
-
1) 为循环设置固定大小不是一个好主意。它应该基于网格行(如果你坚持这条路线)。 2) 如果您的任何 [Description] 值包含撇号 ('),您将收到错误消息。 3)通过循环的每次迭代,当您调用 myAdapter.Fill(mySet, "t_rules") 时,您将覆盖您的数据集。所以在一个循环中重新查询会打败你的数据库。您应该只运行最后一个查询,因为这是您要保留的唯一结果集。
标签: c# sql data-binding datagridview connection