Home > Enterprise >  Problem with selecting data from a database using .NET c# Application
Problem with selecting data from a database using .NET c# Application

Time:10-09

try
{
    //insert data into database
    //check if data already exists
    using (SqlConnection con = new SqlConnection(@"Server=DESKTOP-31579CJ\SQLEXPRESS;Database=LoginInformation;Trusted_connection = True;"))
    { 
        SqlCommand cmd = new SqlCommand(@"SELECT User.Username FROM User WHERE Username = '"   Username.Text   "'", con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            MessageBox.Show("Username already exists");
        }
        else
        {
            MessageBox.Show("Account created");
            cmd = new SqlCommand(@"INSERT INTO User (Username,Password) VALUES ('"   Username.Text   "','"   Password.Password   "')", con);

            cmd.ExecuteNonQuery();
            //clear textboxes
            Username.Text = "";
            Password.Password = "";
        }
        dr.Close();
        con.Close();
    }
}
catch (Exception ex)
{
    MessageBox.Show("Exception occured"   ": "   ex.Message);
    SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-31579CJ\SQLEXPRESS;Initial Catalog=LoginInformation;Integrated Security=True;User ID = yes; Password = yes");
    //create table if one does not exist
    SqlCommand cmd = new SqlCommand("CREATE TABLE User (Username varchar(50), Password varchar(50))", con);
}

When I attempt to execute this query I am met with the exception:

Incorrect syntax near the keyword 'User'

but I haven't really used C# or SQL that often so I honestly couldn't see the problem -- Any feedback on this code will also be appreciated

CodePudding user response:

I haven't checked to confirm but I'm guessing that "User" is a reserved word in T-SQL so you would need to escape it:

SqlCommand cmd = new SqlCommand(@"SELECT Username FROM [User] WHERE Username = '"   Username.Text   "'", con);

Note that I have removed the table qualifier from the column name. You can include it but it's rather pointless in a statement that involves a single table. If you do include it, you'd need to escape that too.

You'll have to do the same thing in your other SQL too. "Password" may also be a reserved word - it is in Access but I'm not sure about SQL Server.

This is beyond the scope of this question but you really ought to not use string concatenation to insert values into SQL either. It's very bad practice that can lead to various issues, including malicious users potentially corrupting or deleting your entire database. Learn how to use parameters immediately. Here is my take on the subject.

  • Related