我只是试图寻找由用户作为参数传递的注册,但它不会返回任何内容或者没有填充DataGridView。
我可以做错什么?
public void getLikeConta(string parametroWhere, string parametroCondicao, DataGridView dataGrid)
{
var query = "SELECT nome,usuario,email,administrador FROM GSCUsuarios WHERE @parametroWhere = @parametroCondicao";
SqlConnection con = BancoDados.Criarconexao();
con.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, con);
dataAdapter.SelectCommand.Parameters.AddWithValue("parametroWhere", parametroWhere);
dataAdapter.SelectCommand.Parameters.AddWithValue("parametroCondicao", parametroCondicao);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGrid.ReadOnly = true;
dataGrid.DataSource = ds.Tables[0];
commandBuilder.Dispose();
con.Close();
con.Dispose();
}
方法的调用在哪里传递参数
private void btnPesquisar_Click(object sender, EventArgs e)
{
Classes.Contas conta = new Classes.Contas();
switch (cboFiltro.SelectedIndex)
{
case 0:
conta.getLikeConta("nome", txtBusca.Text, gridConsultaUsuario);
configuraDataGridView();
//gridConsultaUsuario.DataSource = conta.getContas("nome", txtBusca.Text).Tables[0];
break;
case 1:
conta.getLikeConta(txtBusca.Text, "usuario", gridConsultaUsuario);
//gridConsultaUsuario.DataSource = conta.getContas("usuario", txtBusca.Text).Tables[0];
break;
case 2:
conta.getLikeConta(txtBusca.Text, "setor", gridConsultaUsuario);
break;
case 3:
conta.getLikeConta(txtBusca.Text, "cargo", gridConsultaUsuario);
break;
default:
break;
}
}
答案 0 :(得分:1)
问题是您可以使用字段名称作为参数,您必须在查询中写入字段名称,如下所示:
public void getLikeConta(string parametroWhere, string parametroCondicao, DataGridView dataGrid)
{
var query = string.Format("SELECT nome,usuario,email,administrador FROM GSCUsuarios WHERE {0} = @parametroCondicao", parametroWhere);
SqlConnection con = BancoDados.Criarconexao();
con.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(query, con);
dataAdapter.SelectCommand.Parameters.AddWithValue("parametroCondicao", parametroCondicao);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGrid.ReadOnly = true;
dataGrid.DataSource = ds.Tables[0];
commandBuilder.Dispose();
con.Close();
con.Dispose();
}
您可以尝试在SQL Server中执行此操作,第一个查询将起作用,但会带来0行,但第二个查询将有数据。
declare @parametroWhere nvarchar(max), @parametroCondicao nvarchar(max)
set @parametroWhere=N'nome'
set @parametroCondicao=N'some value that exist in db'
--first query
SELECT nome,usuario,email,administrador FROM GSCUsuarios WHERE @parametroWhere = @parametroCondicao
--second query
SELECT nome,usuario,email,administrador FROM GSCUsuarios WHERE nome = @parametroCondicao