Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

c# - How to use string variable in sql statement

I have a WPF Application in which I am getting

string someone = TextBox.text;

I would like to use this in the following query

query = " Select * From Table Where Title = someone "

How should I go about using the variable someone in the query?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can just do this

query = "Select * From Table Where Title = " + someone;

But that is bad and opens you to SQL Injection

You should just use a parameterized query

Something like this should get you started

using (var cn = new SqlClient.SqlConnection(yourConnectionString))
using (var cmd = new SqlClient.SqlCommand())
{
   cn.Open();
   cmd.Connection = cn;
   cmd.CommandType = CommandType.Text;
   cmd.CommandText = "Select * From Table Where Title = @Title";
   cmd.Parameters.Add("@Title", someone);
}

From Jon Skeet's answer since his was more complete than mine

See the docs for SqlCommand.Parameters for more information.

Basically you shouldn't embed your values within the SQL itself for various reasons:

  • It's inelegant to mix code and data
  • It opens you up to SQL injection attacks unless you're very careful about escaping
  • You have to worry about formatting and i18n details for things like numbers, dates and times etc
  • When the query remains the same with only the values changing, the optimizer has less work to do - it can look up the previous optimized query directly as it'll be a perfect match in terms of the SQL.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...