我正在使用C#,VS 2005和SQL 2000
我的代码是:
StringBuilder sb = new StringBuilder();
sb.Append("insert into dummy(name,amount)values");
foreach (Control ctl in this.flowLayoutPanel1.Controls)
{
if (ctl.Name.Contains("tb") && ctl is TextBox)
{
sb.Append(ctl.Text);
}
}
foreach(Control bbl in this.flowLayoutPanel1.Controls)
{
if(bbl.Name.Contains("bb") && bbl is TextBox)
{
sb.Append(bbl.Text);
}
}
SqlCommand cmd = new SqlCommand(sb.ToString(), con);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
它会抛出这样的错误:
值附近的语法不正确
请帮帮我。
答案 0 :(得分:1)
看起来你在括号之后和VALUES
后遗漏了一个空格。您错过了VALUES
声明的开始和结束括号。您还需要在插入的值之后添加逗号以分隔它们。所以你的语法应该类似于:
insert into dummy(name,amount) values (textBox1value, textBox2value)
修改强>
假设您的flowLayoutPanels中只有2个TextBox控件,那么您可以执行以下操作:
StringBuilder sb = null;
sb = new StringBuilder();
sb.Append("insert into dummy(name,amount)values (");
foreach (Control ctl in this.flowLayoutPanel1.Controls)
{
if (ctl.Name.Contains("tb") && ctl is TextBox)
{
sb.Append(ctl.Text);
}
}
sb.Append(",");
foreach(Control bbl in this.flowLayoutPanel1.Controls)
{
if(bbl.Name.Contains("bb") && bbl is TextBox)
{
sb.Append(bbl.Text);
}
}
sb.Append(")");
但是,我会强烈研究Jon建议的解决方案。
答案 1 :(得分:1)
答案 2 :(得分:1)
值本身需要放在括号中,并用逗号分隔。
我认为你的代码产生了这个:
insert into dummy(name,amount)valuesthisname100
但你需要改变它来产生这个:
INSERT INTO dummy (name, amount) VALUES ('thisname', 100)
执行此操作的一些示例代码是:
StringBuilder sb = null;
sb = new StringBuilder();
sb.Append("insert into dummy(name,amount)values (");
foreach (Control ctl in this.flowLayoutPanel1.Controls)
{
if (ctl.Name.Contains("tb") && ctl is TextBox)
{
sb.Append("'" + ctl.Text + "'");
}
}
sb.Append(", ");
foreach(Control bbl in this.flowLayoutPanel1.Controls)
{
if(bbl.Name.Contains("bb") && bbl is TextBox)
{
sb.Append(bbl.Text);
}
}
sb.Append(")");
SqlCommand cmd1 = new SqlCommand(sb.ToString(), con);
cmd1.CommandType = CommandType.Text;
cmd1.ExecuteNonQuery();
这段代码远非理想,但应修复SQL语法错误。您应该考虑的其他一些增强功能是:
然而,更好的方法是做到这一点( EDITED 以帮助mahesh编码,现在包含多个插入内容):
string sName = null;
double? nAmount = null;
foreach (Control ctl in this.flowLayoutPanel1.Controls)
{
if (ctl.Name.Contains("tb") && ctl is TextBox) sName = ctl.Text;
if (ctl.Name.Contains("bb") && ctl is TextBox)
{
double nTmp = 0;
if (double.TryParse(ctl.Text, out nTmp)) nAmount = nTmp;
}
if (sName != null && iAmount != null)
{
SqlCommand cmd1 = new SqlCommand("INSERT INTO dummy (name, amount) VALUES (@name, @amount)", con);
cmd1.Parameters.Add("@name", SqlDbType.VarChar).Value = sName;
cmd1.Parameters.Add("@amount", SqlDbType.Decimal).Value = nAmount;
cmd1.ExecuteNonQuery();
sName = null;
nAmount = null;
}
}