使用准备好的语句进行C#SQL搜索

问题描述

我不熟悉使用预备语句和SQL查询,因此,如果这是一个简单的解决方法,请原谅。

我有一个显示如下数据的数据库

Data grid view example

ComboBox允许用户搜索添加删除数据库条目。最近有人告诉我要使用准备好的语句(实际上应该将其作为标准来教)。在我的add方法中实现准备好的语句效果非常好,但是在我的搜索方法中执行类似操作时,出现以下错误1错误1可在下面的LoadDataView方法中找到(我已标记了确切的行)。

Exception screenshot

搜索方法

private void SearchProduct()
    {
        using (sqlConnection sqlCon = new sqlConnection(connectionString))
        {
            //open database (close below)
            sqlCon.open();

            //sql query that inserts data into table using user inputs
            String query = "SELECT * FROM Product WHERE ProductCode LIKE @ProductCode OR Range LIKE @Range OR Type LIKE @Type OR Size LIKE @Size " +
                "OR Description LIKE @Description OR Barcode LIKE @Barcode";

            //initialise sqlcommand using the query and connection
            using var command = new sqlCommand(query,sqlCon);

            //assign values and prepare them
            command.Parameters.Add("@ProductCode",sqlDbType.VarChar,25).Value = txbx_ProductCode.Text;
            command.Parameters.Add("@Range",20).Value = txbx_Range.Text;
            command.Parameters.Add("@Type",50).Value = txbx_Type.Text;
            command.Parameters.Add("@Size",15).Value = txbx_Size.Text;
            command.Parameters.Add("@Description",100).Value = txbx_Description.Text;
            command.Parameters.Add("@Barcode",13).Value = txbx_Barcode.Text;

            //prepare the added statements
            command.Prepare();
            //execute using nonqeury (cause of no expected return data)
            command.ExecuteNonQuery();

            //update datagrid with database after search
            LoadDataView(query);

            //close database (open above)
            sqlCon.Close();
        }
    }

发生错误方法(当我在搜索方法调用LoadDataView时发生)

private void LoadDataView(String query)
    {
        using (sqlConnection sqlCon = new sqlConnection(connectionString))
        {
            //open database connection (closed below)
            sqlCon.open();

            //create adapter and datatable,pull all data from database using connection
            sqlDataAdapter sqlAdapter = new sqlDataAdapter(query,sqlCon);
            DataTable dtaTable = new DataTable();

            //fill datagrid with database data using the adapter
            //
            //this is where error [1] occurs
            //
            sqlAdapter.Fill(dtaTable);

            //fill datagridview with database data
            dgv_display.DataSource = dtaTable;

            //close connection (opened above)
            sqlCon.Close();
        }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)