0

I am writing a small XAML/C#/MySQL database and wanted to create a query that accepts parameters. However, the test query that I am setting up fails when I try to create it

    var con = new MySqlConnection(ClsVariables.StrDb);
    con.Open();
    var command = new MySqlCommand("", con);

command =
    new MySqlCommand("Create View r2_Add_Edit_View as SELECT era.contact_id, era.n_family FROM era WHERE era.contact_id = @ContactID", con)            command.ExecuteNonQuery();
    con.Close();

When I change the @ContactID to a specific number - it works fine.

After that I will need to create a recordset, and pass the parameter to it (but I can ask that in a secondary question).

Thanks as always.

1
  • Please post full code Commented May 7, 2014 at 16:27

2 Answers 2

1

When I change the @ContactID to a specific number - it works fine.

Well, you don't pass the parameter, so just add it to your command:

public class MySqlConnector
{
    private readonly string _connString;

    public MySqlConnector(string connString)
    {
        _connString = connString;
    }

    private MySqlCommand _command;
    const string Sql = "Create View r2_Add_Edit_View as SELECT era.contact_id, era.n_family FROM era WHERE era.contact_id = @ContactID";

    public void CreateView(int contactId)
    {
        if(_command == null)
        {
            _command = new MySqlCommand();

            _command.CommandText = Sql;
            _command.Connection = _connString;
        }
        _command.Parameters.AddWithValue("@ContactID", contactId);
        _command.ExecuteNonQuery();
        _command.Close();
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Yair - I want it to be something that I can call from within the C# app, so don't really want to create a new query each time.
You don't have to create a new query. You can cache the command object in the class and just set different parameters each time.
Sorry I'm a bit new to this - so not quite sure how to do that. Also wouldn't that mean that the query won't be compiled.
@AndyDB See my update with a caching support for the command object.
Thanks Yari - but when I run that code, I get an exception error on the ExecuteNonQuery: An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
|
0

Try to use Command AddParameters method.

command.Parameters.Add("@ContactID", SqlDbType.Int);

command.Parameters["@ContactID"].Value = value;

3 Comments

I'm a bit new to this, could you give me a bit more help please.
Google says this link should help you.
Thanks Gigi - Whilst that is interesting, it's not what I'm after here.

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.