string s = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection c = new SqlConnection(s);
SqlCommand cmd;
string a = @"insert into login(user name) values ('"+TextBox1.Text+"')";
cmd = new SqlCommand(a,c);
c.Open();
cmd.ExecuteNonQuery();
c.Close();

- 649
- 4
- 7
-
2Your `INSERT` query is invalid. It is also open to SQL injection, which is another (quite serious) problem. – Frédéric Hamidi Jan 08 '14 at 15:31
-
If `user name` is the actual column name, you'll need to qualify it as `insert into login([user name]) values ...` – StuartLC Jan 08 '14 at 15:32
3 Answers
Fields that contains spaces in their names should be enclosed in square brackets
string s = @"Data Source=.....";
using(SqlConnection c = new SqlConnection(s))
using(SqlCommand cmd = new SqlCommand("insert into login([user name]) " +
"values (@uname)", c))
{
c.Open();
cmd.Parameters.AddWithValue("@uname", textbox1.Text);
cmd.ExecuteNonQuery();
}
Also keep in mind that string concatenation to build sql commands is a real error also when your code seems to work. You are exposed to Sql Injection and suddenly you code doesn't work anymore when someone try to insert a username with a quotes inside.
Instead a parameterized query like the one above remove these weakly points.
By the way, while you still can, change that field name and remove the space. There is no gain in using it and every future query will be affected by this annoying problem (missing brackets)
Surround your user name
column with brackets (If it actually contains spaces):
string a = @"insert into login([user name]) values ('"+TextBox1.Text+"')";
You should also use Parameterized Queries

- 21,581
- 7
- 51
- 66
If the user name
column has space then surround it with quotes
string a = @"insert into login(\"user name\") values ('"+TextBox1.Text+"')";
If user name column does not have space between user and name then you should user username
string a = @"insert into login(username) values ('"+TextBox1.Text+"')";

- 146,340
- 25
- 209
- 204