Selman ALPDÜNDAR

Using PostgreSQL Stored Procedure with Parameter in Xamarin Forms

I posted a blog about reading data from PostgreSQL  in Xamarin forms actually  almost ever thing same but now we need to add parameter and  declare which type command we will use.
Let’s start coding with connecting database.

string ConnectionString = "Server="Server ip or local ip"; Port=5432; User Id="your user name"; Password="your password";
Database="your database name";
try{ 
    NpgsqlConnection connection = new NpgsqlConnection(ConnectionString);
    connection.Open();
}catch(Exception ex){ 
  Console.WriteLine(ex.ToString()); 
}

After connection database now we will code command.

  NpgsqlTransaction tran = connection.BeginTransaction();
  NpgsqlCommand command = new NpgsqlCommand("your function name", connection);
  command.CommandType = CommandType.StoredProcedure;
  command.Parameters.Add(new NpgsqlParameter());
  command.Parameters[0].NpgsqlDbType = NpgsqlDbType.Boolean
  command.Parameters[0].Value = true;

In above code the function which is in your database take one parameter. If you want to use more than one parameter just repeat adding parameter part like

  NpgsqlTransaction tran = connection.BeginTransaction();
  NpgsqlCommand command = new NpgsqlCommand("your function name", connection);
  command.CommandType = CommandType.StoredProcedure;
  command.Parameters.Add(new NpgsqlParameter());
  command.Parameters[0].NpgsqlDbType = NpgsqlDbType.Boolean
  command.Parameters[0].Value = true;
  command.Parameters.Add(new NpgsqlParameter());
  command.Parameters[0].NpgsqlDbType = NpgsqlDbType.Boolean
  command.Parameters[0].Value = false;

All issues is here adding parameter type and parameter value.
After this you can read all data from database.

NpgsqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM your table name";
try{
    NpgsqlDataReader reader = command.ExecuteReader();
 
while (reader.Read()) {
    string Id= reader[0].ToString();
    string Name = reader[1].ToString();
 }
    connection.Close();
 
 }catch(Exception ex){
    Console.WriteLine(ex.ToString());
 }


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.