我正在尝试将SQL查询中的数据放入DataGridview,但是当我尝试运行该程序时,我得到了异常
必须声明标量变量@cathedra
以下是代码:
string connectionString = "user id=bogdan_db; password=1234;server=localhost; Trusted_Connection=yes; database=cafedrascience; connection timeout=30";
string sql = @"select *
from researc r inner join research_cafadra rc on r.id = rc.researc_id
inner join cathedra c on c.id = rc.cafadre_id
where c.name like @Cathedra;";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("@Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
connection.Open();
command.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString); //c.con is the connection string
DataTable table = new DataTable();
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
我在哪里错了?
答案 0 :(得分:3)
问题是您要执行两次查询(并且还连接到数据库两次)。请删除command.ExecuteNonQuery()
并更改
SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, connectionString);
到
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
答案 1 :(得分:0)
您已将参数添加到command
,如果您实际使用的是command
,则该参数是正确的。你不是......你打电话给ExecuteNonQuery()
而不做任何其他事情。
您可以删除这些行:
command.Parameters.Add("@Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text.ToString();
command.ExecuteNonQuery();
在创建dataAdapter
后添加此内容:
dataAdapter.SelectCommand.Parameters.Add("@Cathedra", SqlDbType.VarChar, 50).Value = comboBox1.Text;