多个参数占用C#中的多行

时间:2021-11-17 15:53:50

I am trying to develop a C# windows form application using visual studio. It connects to a microsoft access database. I have a form that saves data to the database. I have text boxes that I need to link to the database field. My problem is I have a lot of textbox names and values for the textbox to code so I need to do it on multiple lines. I did a search on this site and I see you can use the @ symbol in front of the first set of double quotes which encases the first group of parameters but I am not sure how to deal withe the second group of parameters which is the list of values. It would be something like:

我正在尝试使用visual studio开发一个C#窗体应用程序。它连接到微软访问数据库。我有一个将数据保存到数据库的表单。我有需要链接到数据库字段的文本框。我的问题是我有很多文本框名称和值的文本框代码所以我需要在多行上做。我在这个网站上搜索了一下,我看到你可以在第一组双引号前面使用@符号,它包含第一组参数,但我不知道如何处理第二组参数列表价值观它会是这样的:

command.CommandText = @"insert into xxx (xx,xx,xx,xx,xx,xx,xx)

but when it gets to

但是当它到达时

values('" + txt_ID.Text + "','" + txt_Nickname.Text + "')"

I get an error saying

我说错了

"newline in constant"

“不断换行”

and that it expects either a ";" or a "}".

并且它期望要么“;”或者是“}”。

So basically I have to set of parameters that I am trying to code on multiple lines.

所以基本上我必须设置我试图在多行上编码的参数。

1 个解决方案

#1


4  

You should use parameterized queries:

您应该使用参数化查询:

command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (@id, @nickname)";

OleDbParameter[] parameters = new OleDbParameter[2];
parameters[0] = new OleDbParameter("@id", Convert.ToInt32(txt_ID.Text));
parameters[1] = new OleDbParameter("@nickname", txt_Nickname.Text);

command.Parameters.AddRange(parameters);

Keep in mind that the parameters must be added in the same order they appear in the query. OleDb doesn't use the names but only the order.

请记住,参数必须按照它们在查询中出现的顺序添加。 OleDb不使用名称,只使用订单。

That is why you could use "?" as placeholders in the query with the exact same result

这就是为什么你可以使用“?”作为查询中的占位符具有完全相同的结果

command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (?, ?)";

#1


4  

You should use parameterized queries:

您应该使用参数化查询:

command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (@id, @nickname)";

OleDbParameter[] parameters = new OleDbParameter[2];
parameters[0] = new OleDbParameter("@id", Convert.ToInt32(txt_ID.Text));
parameters[1] = new OleDbParameter("@nickname", txt_Nickname.Text);

command.Parameters.AddRange(parameters);

Keep in mind that the parameters must be added in the same order they appear in the query. OleDb doesn't use the names but only the order.

请记住,参数必须按照它们在查询中出现的顺序添加。 OleDb不使用名称,只使用订单。

That is why you could use "?" as placeholders in the query with the exact same result

这就是为什么你可以使用“?”作为查询中的占位符具有完全相同的结果

command.CommandText = "INSERT INTO mytable (id, nickname) VALUES (?, ?)";