In this tutorial, I will share to you how to make functions for performing basic SQL command such as INSERT, UPDATE, and DELETE. For this tutorial I will add 3 more functions that needed to perform SQL basic commands (INSERT, UPDATE, and DELETE). This is the function for INSERT new record to tb_music table.
// Insert new record to tb_music.
public void insertRecord(Int32 id, String title, String artist)
{
openConnection();
try
{
// Create insert command.
NpgsqlCommand command = new NpgsqlCommand("INSERT INTO " +
"tb_music(id, title, artist) VALUES(:id, :title, " +
":artist)", connection);
// Add paramaters.
command.Parameters.Add(new NpgsqlParameter("id",
NpgsqlTypes.NpgsqlDbType.Integer));
command.Parameters.Add(new NpgsqlParameter("title",
NpgsqlTypes.NpgsqlDbType.Varchar));
command.Parameters.Add(new NpgsqlParameter("artist",
NpgsqlTypes.NpgsqlDbType.Varchar));
// Prepare the command.
command.Prepare();
// Add value to the paramater.
command.Parameters[0].Value = id;
command.Parameters[1].Value = title;
command.Parameters[2].Value = artist;
// Execute SQL command.
int recordAffected = command.ExecuteNonQuery();
if (Convert.ToBoolean(recordAffected))
{
showInformation("Data successfully saved!");
}
}
catch (NpgsqlException ex)
{
showError(ex);
}
closeConnection();
}