0

I wrote an SQL insert method in C # and would like to convert it, so that the rubrics (username, victories, defeats) can be changed with @ and Parameters.AddWithValue. How can I solve this problem

SqlConnection con = new SqlConnection(@"Data Source=******;Initial Catalog=UserDB;Integrated Security=True");

SqlCommand cmdinsert = new SqlCommand("Insert UserTabelle values('" + 0 + "','" + 0 + "','" + txtBenutzerName.Text + "')", con);
con.Open();                    
cmdinsert.CommandType = CommandType.Text;

cmdinsert.ExecuteNonQuery();
con.Close();

MessageBox.Show("Account erfolgreich erstellt");

Login login = new Login(txtBenutzerName.Text);
login.Show();
this.Close();
4
  • 1
    Insert UserTabelle values how about INTO? Commented Apr 24, 2018 at 7:05
  • 2
    Did you look at a prepared statement tutorial? If so - what did you not understand about it? Commented Apr 24, 2018 at 7:06
  • I think he is looking for a parameterized query Commented Apr 24, 2018 at 7:08
  • As an advice, always do write the fields that will be inserted. It table has new columns added your code would fail. Commented Apr 24, 2018 at 8:13

1 Answer 1

1

Use the following code as an example.

            using (var connection =
                new SqlConnection(
                    @"Data Source=******;Initial Catalog=UserDB;Integrated Security=True"))
            {
                connection.Open();
                using (var command =
                        new SqlCommand(
                            @"
insert into UserTabelle([Name], [Other])
values (@name, @other)",
                            connection)){
                    command.Parameters.AddWithValue("@name", txtBenutzerName.Text);
                    command.Parameters.AddWithValue("@other", "some value");
                    command.ExecuteNonQuery();
                }
                connection.Close();
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.