Variable in literal string C #

6

Having this code:

' string s ="insert into Administrador values('"+admin.nick+"','"+admin.pass+"','"+admin.nombre+"');";'

There would be some way to do something like:

string s = @"insert into Administador values('admin.nick','admin.pass','admin.nombre';"; 

Do you necessarily have to do it like the first way?

    
asked by Ricardo Rodriguez 09.05.2017 в 13:04
source

3 answers

11

You can use the Interpolated Chains (necessary C # 6.0):

string s =$"insert into Administrador values('{admin.nick}','{admin.pass}','{admin.nombre}')";

But if you are talking about sql queries, what you should use is a parameterized query, something like:

string s = "insert into Administador values(@nick,@pass,@nombre)"; 
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(s, connection);
    command.Parameters.Add("@nick", SqlDbType.VarChar);
    command.Parameters["@nick"].Value = admin.nick;
    command.Parameters.Add("@pass", SqlDbType.VarChar);
    command.Parameters["@pass"].Value = admin.pass; 
    command.Parameters.Add("@nombre", SqlDbType.VarChar);
    command.Parameters["@nombre"].Value = admin.nombre;

    //ejecutar command ...
}

Parameterized queries allow you to avoid SQL Injections , as well as solve many problems with data types such as the dates. They should be used ALWAYS.

    
answered by 09.05.2017 / 13:15
source
2

What you're looking for in C # is called string Interpolation and is allowed from C # 6:

It allows you to convert the query that you bring:

string s ="insert into Administrador values('"+admin.nick+"','"+admin.pass+"','"+admin.nombre+"')

In something like the following:

string s = $"insert into Aministrador values('{admin.nick}', '{admin.pass}', '{admin.nombre}')";

Its syntax is a literal $ before string to assign or use.

    
answered by 09.05.2017 в 13:21
2

Another option is to use string.format :

  

Converts the value of objects to strings based on the formats   specified and inserts them into another string.

Changing your code would look like this:

string s = "insert into Administrador values('{0}','{1}','{2}');";
string s1 = string.Format(s, admin.nick, admin.pass, admin.nombre);

Example:

Assuming that the values of your variables are the following:

admin.nick = "user1";
admin.pass = "pass1";
admin.nombre = "name";

The result of using string.Format would be the following:

insert into Administrador values('user1','pass1','name');
    
answered by 09.05.2017 в 16:20