Search code examples
c#sqlsql-serversqlconnection

What is the better way of making an SQL statement in Visual Studio?


I was looking up how to insert into my database via sql and I noticed the way I had seen a person do an sql statement was different from the way I had done it and and now I'm wondering which way is better.

An example of what I had done in a previous (select) statement.

SqlConnection conn = new SqlConnection(Variables.Default.sqlConString);
conn.Open();
string builtCmd = Variables.Default.returnUserNameSql1 + usersInput + Variables.Default.returnUsernameSql2;
SqlCommand cmd = new SqlCommand(builtCmd, conn);

usersInput is a string.
Variables.Default.returnUserNameSql1 = SELECT [Username] from [dbo].[LoginDetails] WHERE [Username] = '
returnUsernameSql2 = '

What I have seen online (not my query):

cmd.CommandText = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";

cmd.Parameters.Add(new SqlParameter("@param1", klantId));
cmd.Parameters.Add(new SqlParameter("@param2", klantNaam));
cmd.Parameters.Add(new SqlParameter("@param3", klantVoornaam));

Is the use of the Parameters function (?) better? If so in what way?

Thanks for your time.

I modified my original query thanks to the help of some of the comments here. I'll post it if anyone's interested:

using (SqlConnection conn = new SqlConnection(Variables.Default.sqlConString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(Variables.Default.returnUserNameSql, conn))
                    {
                        cmd.Parameters.Add(new SqlParameter(Variables.Default.param1, usersInput));
                        SqlDataReader reader = cmd.ExecuteReader();
                        usernameTaken = reader.Read();
                        cmd.Dispose();
                    }
                    conn.Close();
                }

Solution

  • Look up "SQL Injection attack" on google. Bobby Tables says hello. And then realize that your way is not bad, it is a security nightmare because everyone with access to your program can execute whatever SQL he wants.