以下是代码段
string search = textBox1.Text;
int s = Convert.ToInt32(search);
string conn="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Data.accdb";
string query="SELECT playerBatStyle FROM Player where playerID='" + s + ";
OleDbDataAdapter dAdapter=new OleDbDataAdapter (query ,conn );
OleDbCommandBuilder cBuilder=new OleDbCommandBuilder (dAdapter );
DataTable dTable=new DataTable ();
dAdapter .Fill (dTable );
dataGridView1.DataSource = dTable;
答案 0 :(得分:1)
你的where子句中有一个未公开的单引号。试试这个:
string query = String.Format("SELECT playerBatStyle FROM Player where playerID={0}", s);
答案 1 :(得分:1)
正如其他人提到的那样,s的类型为int,因此在查询中不需要引号,并且您需要数据绑定行。
此外,如果您还没有,在尝试将其转换为整数之前,您需要检查文本框中是否存在实际值。您不需要OleDbCommandBuilder,因为DataAdapter在内部处理命令作为SelectCommand属性。绝对考虑使用参数化查询,这将减少sql注入漏洞。
以下结合我的建议:
if (textBox1.Text != "")
{
string search = textBox1.Text;
int s = Convert.ToInt32(search);
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Local Docs\\Temp\\Data.accdb";
string query = "SELECT playerBatStyle FROM Player where playerID=@playerID";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, conn);
dAdapter.SelectCommand.Parameters.AddWithValue("@playerID", s);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
dataGridView1.DataSource = dTable;
dataGridView1.DataBind();
}
答案 2 :(得分:0)
您发布的代码看起来不错。但是有一些更正:
...
//fix lots of missing quotation marks
string query="SELECT playerBatStyle FROM Player where playerID='" + s + "' ";
...
dataGridView1.DataBind(); //yes, we should call DataBind
答案 3 :(得分:0)
PlayerID
向我显示int
类型,这意味着您不需要在其周围添加单引号
string query = "SELECT playerBatStyle FROM Player where playerID=" + s + ";
如果要在DataGridView中显示结果,最后你必须dataGridView1.DataBind();
在旁注中,始终建议用户parametrized query而不是在查询中汇总值,这是不安全的
答案 4 :(得分:0)
查看this example是否可以为您提供帮助,
问候。
答案 5 :(得分:0)
使用此查询检索与用户搜索相关的数据
"Select playerBatStyle from Player where Player like %'"+s+"'";