简体   繁体   English

如何将变量连接到SqlCeCommand?

[英]How do i concatenate a variable to a SqlCeCommand?

I'm taking a C# course at the moment and am trying to get some data from my database. 我目前正在上C#课程,并试图从数据库中获取一些数据。

In my public function I have a local variable: string genre = "drama"; 在我的公共函数中,我有一个局部变量: string genre = "drama";

Now I want to concatenate that variable to my SqlCeCommand: 现在,我想将该变量连接到我的SqlCeCommand:

SqlCeCommand command = new SqlCeCommand("SELECT * FROM Movie WHERE Genre =" + genre, connection);

But I am not able to. 但是我不能。

So my question is: How do I append, or concatenate a variable to a SqlCeCommand? 所以我的问题是:如何将变量附加或连接到SqlCeCommand?

SqlCeCommand command = new SqlCeCommand("SELECT * FROM Movie WHERE Genre = @genre", connection);
command.Parameters.AddWithValue("@genre", genre);

your first attempt was close ,and can work if the syntax is fixed, but using parameters will help prevent injection attacks, which can be very bad. 您的第一次尝试是close,并且在语法固定的情况下可以使用,但是使用参数将有助于防止注入攻击,这可能非常糟糕。

You should always use SQL parameters instead of string concatenation, to prevent SQL injection. 您应该始终使用SQL参数而不是字符串连接,以防止SQL注入。 In your case, this will also make it easier for you to write a valid SQL query: 就您而言,这也将使您更容易编写有效的SQL查询:

SqlCeCommand command = new SqlCeCommand("SELECT * FROM Movie WHERE Genre = @genre", connection);
command.Parameters.AddWithValue("@genre", genre);

Use parameters 使用参数

  SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM Movie WHERE Genre = @genre", conn));
  cmd.Parameters.Add(new SqlCeParameter("@genre", genre));

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

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