简体   繁体   English

在SQL语句中使用ComboBox选择

[英]Using ComboBox selection in SQL statements

I would like to insert a number, for example 112, into a table cell. 我想在表格单元格中插入一个数字,例如112。 The column should be selected from a ComboBox. 该列应从ComboBox中选择。 For example, if combobox1 text is "name", then data should be inserted into column "name" in table1. 例如,如果combobox1文本为“ name”,则应将数据插入table1中的“ name”列中。

The code below does not seem to work: 下面的代码似乎不起作用:

cmd.CommandText = "INSERT INTO table1 ('" + combobox1.SelectedItem + "') values ('" + txtbox1.Text + "')";

With a hardcoded column name it works: 使用硬编码的列名,它可以工作:

cmd.CommandText = "INSERT INTO table1 (name) values ('" + txtbox1.Text + "')";

How can i insert the ComboBox selection into the statement? 如何将ComboBox选择插入语句中?

Use parameters to protect against SQL Injection . 使用参数来防止SQL注入 Do not add ' for column name. 不要在列名中添加'。

cmd.CommandText = "INSERT INTO table1 (" + combobox1.SelectedItem.ToString() + ") values (@VALUE)";
cmd.Parameters.AddWithValue("@VALUE", txtbox1.Text);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM