首页 > 解决方案 > 在 Xamarin 中打开 Postgres 连接在连接时返回错误

问题描述

我正在尝试将我的 Android 应用程序连接到 Postgres,但似乎无法正常工作。

异常消息是:Exception while Connecting

这是我的代码背后,

 private void Login_Clicked(object sender, EventArgs e)
        {
            DBInterface<DBLogicInput, DBLogicResult> dbLoginLogic = new DBLoginLogic();
            DBLogicInput userInput = new DBLogicInput();
            DBLogicResult DBResult = new DBLogicResult();
            LoginModel useCredentials = new LoginModel()
            {
                userName = txtUsername.Text,
                passWord = txtPassword.Text
            };

            userInput[typeof(LoginModel).FullName] = useCredentials;

            try
            {
                DBResult = dbLoginLogic.DoProcess(userInput);
                bool userExisting = DBResult.ResultCode != DBLogicResult.RESULT_CODE_ERR_DATA_NOT_EXIST;
                if (userExisting)
                {
                    Application.Current.MainPage = new NavigationPage(new IndexPage());
                }
                else
                {

                    _ = DisplayAlert("Login Error", "User does not exist", "Ok");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

这是我为连接数据库而创建的类。

  public abstract class DBLogic : DBInterface<DBLogicInput, DBLogicResult>
    {
        public string connectionString = "Server=localhost;Port=5432;User Id=postgres;Password=postgres;Database=proyektoNijuan";
        public DBLogicResult DoProcess(DBLogicInput inOut)
        {
            //throw new NotImplementedException();
            DBLogicResult result = default(DBLogicResult);
            NpgsqlConnection connection = null;
            NpgsqlTransaction transaction = null;
            try {
                connection = new NpgsqlConnection(connectionString);
                if (connection.State != System.Data.ConnectionState.Open)
                {
                    connection.Open();
                }
                transaction = connection.BeginTransaction();
                result = Process(connection, inOut);
                transaction.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                transaction.Rollback();
            } finally {
                if (connection != null)
                {
                    connection.Close();
                }
            }
            return result;
        }

        protected abstract DBLogicResult Process(NpgsqlConnection conn, DBLogicInput InOuT);
    }

调试器命中代码后,错误就存在了connection.Open();

我应该添加一个 Web 服务来将 postgres 连接到我在 xamarin 表单中构建的 android 应用程序吗?

我只是 Xamarin Forms 的初学者。我只是想创建一个自我应用程序。我需要一点帮助来学习一个新的编程平台。

谢谢和问候,

如何解决?

标签: postgresqlxamarin.forms

解决方案


好吧,我想我做错了。

也许连接 PostgreSQL 的正确方法是拥有一个 WEB API。

将该 Web API 调用到 Xamarin 表单。

我真的不知道它是否正确,但我会尝试一下。

完成该 WEB API 的开发后,我将更新正确答案,以便其他初学者会发现此答案很有帮助。


推荐阅读