【发布时间】:2016-05-25 04:14:32
【问题描述】:
对不起,如果这看起来有点像菜鸟:3 ...我在 C# 方面没有太多经验,但我真的很喜欢用 C# 编写代码,我认为它是一种非常灵活和友好的面向对象语言。
那么好。 我试图通过按钮点击传递变量,以便能够使用按钮点击获得的值插入数据库。我有几个按钮将“产品”值回收到不同的字符串,在自然语言方法中,这将是:
如果我单击某个“产品”,变量产品将获得按钮的名称,然后我将单击“数量”按钮,这将给我数量编号,然后程序将插入具有这些值的数据库。但我怀疑如何根据单击的按钮回收这些值。
简而言之,我的代码如下:
private String product;
private int quantity;
private char prodchosen;
private char quantitychosen;
private void Product_Click(object sender, EventArgs e)
{
prodchosen = 'Y';
product = "Beer";
}
private void Product2_Click(object sender, EventArgs e)
{
prodchosen = 'Y';
product = "Juice";
}
public void bttn1_Click(object sender, EventArgs e)
{
quantitychosen = 'Y';
quantity = 1;
if (prodchosen == 'Y' && quanitychosen == 'Y')
{
MySqlConnection mcon = new MySqlConnection("server=localhost;database=***;username=root;password=***");
mcon.Open();
string insert = "INSERT INTO accounts product, quantity VALUES" + product + " , " + quantity;
MySqlCommand cmd = new MySqlCommand(insert, mcon);
MessageBox.Show("Product was succesfully added");
}
else {
MessageBox.Show("Quantity and product not recognized");
}
插入数据库后,这些值将显示在gridview中,select语句将由组合框selectedindex值分隔,如:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
clientchosen = 'Y';
client_id = comboBox1.SelectedIndex;
MySqlConnection mcon = new MySqlConnection("server=localhost;database=***;username=root;password=***");
mcon.Open();
char open = 'Y';
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
string select2 = "SELECT * FROM account where client_id = " + selectedIndex + " and open = " + open;
MySqlCommand cmd2 = new MySqlCommand(select2, mcon);
object result = cmd.ExecuteNonQuery();
}
到目前为止,我无法成功插入,甚至无法显示消息框,我将非常感谢您对此问题的任何 cmet。
【问题讨论】:
-
插入查询错误...使用 INSERT INTO table_name VALUES (value1,value2,value3,...);
-
调试时会发生什么?是否有错误,我的意思是你的sql语句在值周围缺少“(”和“)”
-
@DDave 插入很好。如果您不向每一列插入数据,则必须指定列名。添加括号会更容易阅读。
标签: c# database visual-studio variables events