微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用准备好的语句进行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 举报,一经查实,本站将立刻删除。