0

I have the following code in my C# Winforms Application. I am using SQL Lite but how do I pass the values from my text boxes into the insert statement:

void InsertConnectionDetails()
{
    m_dbConnection.Open();

    string sql = "insert into rdpdirectory (company, server, username, password) values (txtCompany, txtServer, txtUsername,txtPassword)";
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    command.ExecuteNonQuery();

    m_dbConnection.Close();
    MessageBox.Show("Done");
}
4
  • The answer from Sudhakar is the solution, however, old style preferably to be avoided is concatenation, Values ('"+ TextBox1.Text + "' , '" + TextBox2.Text + etc... Commented Feb 15, 2014 at 17:55
  • 1
    @FeliceM String concatenation in SQL Queries is bad... very bad. Commented Feb 15, 2014 at 17:56
  • 1
    @EvanL I fully agree with you. This is why I said that the solution is the answer given by Sudhakar. Commented Feb 15, 2014 at 17:57
  • Please do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. Commented Feb 15, 2014 at 18:00

1 Answer 1

6

Solution 1: i can tell you that you need to insert the values directly into INSERT INTO Statement but it leads to SQL Injection Attacks and not recommended.

Try This : (I don't Suggest this)

string sql = @"insert into rdpdirectory (company, server, username, password) 
                   values ('"+txtCompany.Text+"', '"+txtServer.Text+"','"+txtUsername.Text+"','"+txtPassword.Text+"')";

Solution 2: So you can Use Parameterised Queries to be in safer side.

Try This: Using Parameterised Queries (I Suggest this)

string sql = @"insert into rdpdirectory (company, server, username, password) 
               values (@company, @server, @username,@password)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.AddWithValue("@company",txtCompany.Text);
command.Parameters.AddWithValue("@server",txtServer.Text);
command.Parameters.AddWithValue("@username",txtUsername.Text);
command.Parameters.AddWithValue("@password",txtPassword.Text);
Sign up to request clarification or add additional context in comments.

1 Comment

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.