如果我想连接到数据库它会崩溃?

时间:2017-11-21 19:40:23

标签: mysql xamarin.ios

using System;
using Xamarin.Forms;
using UIKit;
using MySql.Data.MySqlClient;

namespace test.project
{
    public partial class ViewController : UIViewController
    {

        partial void UIButton197_TouchUpInside(UIButton sender)
        {
            if (textBoxName.Text == "" || textBoxpasswd.Text == "")
            {
                var alert = UIAlertController.Create("Fehler", "Bitte geben sie Benutzername und Password ein", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
                // Fehlerüberprüfung wenn leer ist

            }
            else
            {
                try
                {
                    MySqlConnection con = new MySqlConnection("Server=localhost;Port=8889;database=app;User Id=root;Password=;charset=utf8");

                    if (con.State == System.Data.ConnectionState.Closed)
                    {
                        con.Open();
                        MySqlCommand cmd = new MySqlCommand("INSERT INTO users(id, username, passwd, rank) VALUES(@user, @pass, @rank)", con);
                        cmd.Parameters.AddWithValue("@user", textBoxName.Text);
                        cmd.Parameters.AddWithValue("@pass", textBoxpasswd.Text);
                        cmd.Parameters.AddWithValue("@rank", 0);

                        cmd.ExecuteNonQuery();
                        errorLabel.Text = "ausgeführt";
                    }
                    else
                    {
                        errorLabel.Text = "no connection";
                    }
                }
                catch
                {
                    errorLabel.Text = "catch";
                }
            }
        }

        protected ViewController(IntPtr handle) : base(handle)
        {
            // Note: this .ctor should not contain any initialization logic.
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }
}

我试着。连接到数据库,但在线路开启后,程序崩溃

1 个答案:

答案 0 :(得分:1)

建立与数据库的连接显然存在问题。

您已将服务器定义为:Server=localhost

这绝对正确吗?我非常怀疑你在设备上运行一个完整的MySQL服务器?如果您在设备上运行服务器,服务器进程是否正在运行?

应用程序关闭的执行是什么?

CONNECTION_TIMEOUT?可能是防火墙问题 CONNECTION_REFUSED? MySQL服务器进程未运行。

您还应该将应用程序设计为针对数据库故障进行强化,也可以尝试使用try:

包装连接
try {

    connection.open();

} catch (Exception e) {

    // TODO handle the connection error properly
    System.err.println("An error has occurred.");
    e.printStackTrace();
}
相关问题