0

When I write this line:

SqlCommand MySqlCommand = new SqlCommand("INSERT INTO [User](NAME ,PASSWORD ,PUBLISH_FOLDER,ACTIVE,IP,PORT) Values ('shula','Aa1234','study','true','1015','8080')", MyConnection);

it works but when I write this lines:

string Name = user.Name;

string Password = user.Password;

string Port = (user.Port).ToString();

string publishFolder=user.publishFolder;

string Ip=user.Ip;

SqlCommand MySqlCommand = new SqlCommand("INSERT INTO [User](NAME ,PASSWORD ,PUBLISH_FOLDER,ACTIVE,IP,PORT) Values (" + Name + "," + Password + "," + publishFolder + ",TRUE," + Ip + "," + Port + ")", MyConnection);

the error is:

invalid column name...

Dmitry
  • 13,797
  • 6
  • 32
  • 48
gal kogeman
  • 89
  • 1
  • 1
  • 9
  • 1
    Create the commands string as a string first to see your mistake. Then switch to parameterized queries. – CodeCaster Oct 01 '14 at 21:59
  • 1
    Look carefully your first query. What do you see around the values written to the table? They are not present in the string concatenated query. But please learn about Sql Injection then rewrite everything – Steve Oct 01 '14 at 21:59
  • The values you're using in the second code block need `'` before and after. – hunch_hunch Oct 01 '14 at 22:00
  • 2
    Stop concatenating your SQL. Search this site **now** for "parameterized queries", and start doing it properly. Your current code is highly vulnerable to SQL injection, and attempting to concatenate strings to form SQL leads to the types of problems you're having now. Properly using parameters for your queries will avoid both of those issues. – Ken White Oct 01 '14 at 22:00
  • Yes, because using clearly sql command's dangerous. This object provides parameters. Look here: http://msdn.microsoft.com/pl-pl/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx (translate it to your language) – Marek Woźniak Oct 01 '14 at 22:05
  • 1
    Appart from all the other issues mentioned, don't store passwords in plaintext - use a secure hash + salt (see http://stackoverflow.com/q/829838/21567 for more information). – Christian.K Oct 02 '14 at 07:58

1 Answers1

1

It is because

 "  Values (" + Name + "," 

generates

 Values (shula,

and not

 Values ('shula',

But you should not add the ' but use parameters instead.

H H
  • 263,252
  • 30
  • 330
  • 514