-4
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();
Manoj Mevada
  • 649
  • 4
  • 7

3 Answers3

3

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)

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
1

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

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
0

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+"')";
Adil
  • 146,340
  • 25
  • 209
  • 204