Sharpy2016 Sharpy2016 - 5 months ago 13
SQL Question

C# Sqlcommand textbox with spaces

I am using Visual Studio 2015, Windows Form Application

My SqlCommand works -- except, in the Street column (Street VARCHAR(70)), which gets the input from a textbox (streetTextBox.Text) throws an error if there is a space OR if its not a number. I can manually enter into database just fine and the command works as long as the street textbox is only a number with no spaces.

comm2 = new SqlCommand("insert into Addresses(Street, City, aState, Zip) values (" + streetTextBox.Text + ",'" + cityTextBox.Text + "','" + aStateTextBox.Text + "','" + zipTextBox.Text + "')", conn);



try
{
comm.ExecuteNonQuery();
comm2.ExecuteNonQuery();
MessageBox.Show("Saved...");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}


Why will it not allow an actual street to be saved? (i.e. 555 Street Name)

Answer

Your code is an open door for sql injection attacks. You need to work with parameters instead of concatenating strings into sql.

        comm2 = new SqlCommand("insert into Addresses(Street, City, aState, Zip) values (@Street, @City,@aState, @Zip)", conn);
        comm2.Parameters.Add("@Street", SqlDbType.NVarChar).Value = streetTextBox.Text;
        comm2.Parameters.Add("@City", SqlDbType.NVarChar).Value = cityTextBox.Text;
        comm2.Parameters.Add("@aState", SqlDbType.NVarChar).Value = aStateTextBox.Text;
        comm2.Parameters.Add("@Zip", SqlDbType.NVarChar).Value = zipTextBox.Text;

        try
        {
            comm.ExecuteNonQuery();
            comm2.ExecuteNonQuery();
            MessageBox.Show("Saved...");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            conn.Close();
        }