从文本框传入SQL查询参数

Pri*_*ton 0 c# sqlite winforms

我在C#Winforms应用程序中有以下代码.我正在使用SQL Lite,但如何将文本框中的值传递给insert语句:

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");
}
Run Code Online (Sandbox Code Playgroud)

Sud*_*udi 6

解决方案1:我可以告诉您需要将值直接插入INSERT INTO语句,但它会导致SQL注入攻击,不建议使用.

试试这个:( 我不建议这个)

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

解决方案2:所以你可以使用Parameterised Queries更安全的一面.

试试这个:使用参数化查询(我建议这个)

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);
Run Code Online (Sandbox Code Playgroud)