0

Given the this C# code fragment how do I use a C# variable in the SQL query? I understand the best way to do this is to use "parameters" and I've looked at many examples but I can not "put it together" so far.

   ...
using MySql.Data.MySqlClient;

       public partial class Form1 : Form
        {
            private string server;
            private string database;
            private string uid;
            private string password;
            private MySqlConnection connection;

            public Form1()
            { 
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {

                webBrowser1.Navigate("127.0.0.1/box3.php");

                server = "localhost";
                database = "realestate_db";
                uid = "root";
                password = "";
                string connectionString;
                connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

                connection = new MySqlConnection(connectionString);
                connection.Open();
                MySqlDataAdapter mySqlDataAdapter;
                mySqlDataAdapter = new MySqlDataAdapter("SELECT `ID`, `lat` , `long` FROM `house` ", connection); // want to uses a C# variable in this SQL query

                DataSet DS = new DataSet();
                mySqlDataAdapter.Fill(DS);
                dataGridView1.DataSource = DS.Tables[0];

            }
     ....       

Thanks.
6
  • What's wrong with the code you have now? Error messages? Unexpected behavior? Commented Sep 29, 2014 at 20:30
  • @eddie_cat the code is incomplete. He wants to know how to extend to include something a like a filter in the where clause of the sql string without leaving himself open to sql injection. Commented Sep 29, 2014 at 20:33
  • Whoops, glancing at it I thought he was already trying to parameterize and just having issues getting his code to work. Didn't see the comment. Commented Sep 29, 2014 at 20:35
  • possible duplicate of c# Using Parameters.AddWithValue in SqlDataAdapter Commented Sep 29, 2014 at 20:44
  • @Bearcat9425 I agree it's possibly a duplicate, but let's find a different question to use as the original. The AddWithValue() method is not your friend. Commented Sep 29, 2014 at 20:58

3 Answers 3

1

This is a repeat of a very commonly asked question and I am using code copy and pasted from another article describing, link is here Creating and then working with parameters in queries . You can use the addWithValue method on your dataadapter Select command, or the add method.

da = new MySqlDataAdapter("SELECT `ID`, `lat` , `long` FROM `house` where `ID` = ?ID", connection);
// As most are suggesting Create the parameters with the Add Method, Passing the MySqlDbType  
da.SelectCommand.Parameters.Add("?ID",MySqlDbType.Int32).Value = ID;
 // Can also Use AddWithValue Method as well  
da.SelectCommand.Parameters.AddWithValue("?ID",<Your Variable>);
Sign up to request clarification or add additional context in comments.

8 Comments

If it's very commonly asked you should flag it as a duplicate, not answer it here
You're also answering for Sql not MySql
MySql uses ?'s- see my answer below
Actually that is false i have working code where the @ sysmbol works just fine.
Good to know- odd the MySql doc doesn't say you can use it- but if it works so be it.
|
0

From MySqlDataAdapter

  public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn)
  {
    MySqlDataAdapter da = new MySqlDataAdapter();
    MySqlCommand cmd;
    MySqlParameter parm;
    // Create the SelectCommand.
    cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=?id AND name=?name", conn);
    cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15);
    cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15);
    da.SelectCommand = cmd;
    // Create the InsertCommand.
    cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (?id,?name)", conn);
    cmd.Parameters.Add("?id", MySqlDbType.VarChar, 15, "id" );
    cmd.Parameters.Add("?name", MySqlDbType.VarChar, 15, "name" );

    da.InsertCommand = cmd;  
    return da;
  }

Comments

0

First of all, abstract all your data access out to it's own class or assembly:

public class DAL
{

    private string server = "localhost";
    private string database = "realestate_db";
    private string uid = "root";
    private string password = "";
    private string connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

    public DataSet GetHouse(int ID) 
    {
        //...
    }
}

Then your existing code will call into this method:

public DataSet GetHouse(int ID)
{
    string sql = "SELECT `ID`, `lat` , `long` FROM `house` WHERE ID= ?ID ";
    DataSet result = new DataSet();

    using (var cn = new MySqlConnection(connectionString) )
    using (var cmd = new MySqlCommand(sql, cn) )
    using (var da = new MySqlDataAdapter(cmd) )
    {
       cmd.Parameters.Add("?ID", MySqlDbType.Int32).Value = ID;

       da.Fill(result);
    }
    return result;
}

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.