为什么我的:MySQL连接不起作用?

时间:2016-05-10 17:55:21

标签: c# android

我想与MySQL建立联系,但它不起作用!

我得到的错误:未处理的异常:

  

System.InvalidOperationException:连接必须有效并且打开。

这是我的代码:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "recepten" layout resource
    SetContentView(Resource.Layout.register);

    // Create your application here
    Button back = FindViewById<Button>(Resource.Id.backToLog);
    Button maak = FindViewById<Button>(Resource.Id.maakAccount);
    TextView naam = FindViewById<TextView>(Resource.Id.naam);
    TextView email = FindViewById<TextView>(Resource.Id.email);
    TextView ww = FindViewById<TextView>(Resource.Id.wachtwoord);
    TextView created = FindViewById<TextView>(Resource.Id.succes);

    back.Click += delegate { StartActivity(typeof(login1)); };

    maak.Click += delegate
    {
        MySqlConnection con = new MySqlConnection("Server=db4free.net;Port=3306;database=foodproftaak;User Id=sanderenniek;Password=***;charset=utf8");

        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand("INSERT INTO register(naam, wachtwoord, email) VALUES(@naam, @wachtwoord, @email)", con);
                cmd.Parameters.AddWithValue("@naam", naam);
                cmd.Parameters.AddWithValue("@wachtwoord", ww);
                cmd.Parameters.AddWithValue("@email", email);
                cmd.ExecuteNonQuery();
                created.Text = "You succesfully created an account";
            }
        }
        catch (MySqlException ex)
        {
            created.Text = ex.ToString();
        }
        finally
        {
            con.Close();
        }
    };
}

您诚挚的,

桑德

1 个答案:

答案 0 :(得分:0)

您似乎没有将连接与命令对象相关联。创建MySqlCommand对象后,为其分配连接:

cmd.Connection = con;

或者,您可以在创建MySqlCommand对象时传递连接:

MySqlCommand cmd = new MySqlCommand("INSERT INTO register(naam, wachtwoord, email) VALUES(@naam, @wachtwoord, @email)", con );
相关问题