postgresql - 在 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 的初学者。我只是想创建一个自我应用程序。我需要一点帮助来学习一个新的编程平台。
谢谢和问候,
如何解决?
解决方案
好吧,我想我做错了。
也许连接 PostgreSQL 的正确方法是拥有一个 WEB API。
将该 Web API 调用到 Xamarin 表单。
我真的不知道它是否正确,但我会尝试一下。
完成该 WEB API 的开发后,我将更新正确答案,以便其他初学者会发现此答案很有帮助。
推荐阅读
- sql - SQL 查找平均元组数(既不是最大值也不是最小值)
- linux - 在 Cygwin 上使用 MPI 编译器链接错误?
- javascript - 在 illustrator 中更改选定对象颜色的脚本
- python - 我无法使用硒和美丽的汤来抓取表格数据
- java - 在java中将while循环转换为递归
- javascript - 如何设置 vue 和 core ui?
- java - JavaFX ListChangeListener 删除触发添加更改
- javascript - 使用 JavaScript 在 URL 中添加 GET 参数
- c++ - 将对象插入 std::map 时构造函数中的变量地址
- realm - Realm db 的撤消管理