本文整理汇总了C#中Npgsql.NpgsqlConnection.BeginTransaction方法的典型用法代码示例。如果您正苦于以下问题:C# NpgsqlConnection.BeginTransaction方法的具体用法?C# NpgsqlConnection.BeginTransaction怎么用?C# NpgsqlConnection.BeginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Npgsql.NpgsqlConnection
的用法示例。
在下文中一共展示了NpgsqlConnection.BeginTransaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CleanTables
public static void CleanTables(NpgsqlConnection connection)
{
if (connection == null) throw new ArgumentNullException(nameof(connection));
string script = null;
#if (NETCORE1 || NETCORE50 || NETSTANDARD1_5 || NETSTANDARD1_6)
script = GetStringResource(
typeof(PostgreSqlTestObjectsInitializer).GetTypeInfo().Assembly,
$"Hangfire.PostgreSql.NetCore.Tests.Clean.sql").Replace("'hangfire'", string.Format("'{0}'", ConnectionUtils.GetSchemaName()));
#else
script = GetStringResource(
typeof (PostgreSqlTestObjectsInitializer).Assembly,
"Hangfire.PostgreSql.Tests.Clean.sql").Replace("'hangfire'", string.Format("'{0}'", ConnectionUtils.GetSchemaName()));
#endif
//connection.Execute(script);
using (var transaction = connection.BeginTransaction(IsolationLevel.Serializable))
using (var command = new NpgsqlCommand(script, connection, transaction))
{
command.CommandTimeout = 120;
try
{
command.ExecuteNonQuery();
transaction.Commit();
}
catch (NpgsqlException)
{
throw;
}
}
}
示例2: CleanTables
public static void CleanTables(NpgsqlConnection connection)
{
if (connection == null) throw new ArgumentNullException("connection");
var script = GetStringResource(
typeof (PostgreSqlTestObjectsInitializer).Assembly,
"Hangfire.PostgreSql.Tests.Clean.sql").Replace("'hangfire'", string.Format("'{0}'", ConnectionUtils.GetSchemaName()));
//connection.Execute(script);
using (var transaction = connection.BeginTransaction(IsolationLevel.Serializable))
using (var command = new NpgsqlCommand(script, connection, transaction))
{
command.CommandTimeout = 120;
try
{
command.ExecuteNonQuery();
transaction.Commit();
}
catch (NpgsqlException ex)
{
throw;
}
}
}
示例3: Main
static void Main(string[] args)
{
// Connect to a PostgreSQL database
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; " +
"Password=1905;Database=Lab3;");
conn.Open();
// Start a transaction as it is required to work with result sets (cursors) in PostgreSQL
NpgsqlTransaction tran = conn.BeginTransaction();
// Define a command to call add_ogrenci() procedure
NpgsqlCommand command1 = new NpgsqlCommand("add_ogrenci(9060256,Fatih,Taştemur,01-01-1991,Ankara,50693671313 )", conn);
command1.CommandType = CommandType.StoredProcedure;
NpgsqlCommand command2 = new NpgsqlCommand("count_ogrenci", conn);
command2.CommandType = CommandType.StoredProcedure;
// Execute the procedure and obtain a result set
NpgsqlDataReader dr1 = command1.ExecuteReader();
NpgsqlDataReader dr2 = command2.ExecuteReader();
// Output
while (dr1.Read())
Console.WriteLine("Adding records to a successful");
while (dr2.Read())
return sayi;
tran.Commit();
conn.Close();
}
示例4: PostgresProcessor
public PostgresProcessor(NpgsqlConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options)
: base(generator, announcer, options)
{
Connection = connection;
connection.Open();
Transaction = connection.BeginTransaction();
}
示例5: Salvarcliente
public int Salvarcliente(string nome, int codempresa)
{
using (var conn = new NpgsqlConnection(Connectionstring))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
try
{
int id;
using (var cmd = new NpgsqlCommand("SELECT MIN(PORT_VNC) FROM PORTAS WHERE PORT_VNC NOT iN(SELECT CLIE_IDVNC FROM CLIENTE)", conn, trans))
{
id = int.Parse(cmd.ExecuteScalar().ToString());
}
using (
var cmd =
new NpgsqlCommand(
"INSERT INTO cliente (clie_nome,clie_idvnc, empr_codigo) values ('" + nome + "'," + id + ","+codempresa+")", conn,
trans))
{
cmd.ExecuteNonQuery();
trans.Commit();
return id;
}
}
catch (Exception)
{
trans.Rollback();
return 0;
}
}
}
}
示例6: Append
public void Append(string name, byte[] data, long expectedVersion)
{
using (var conn = new NpgsqlConnection(_connectionString))
{
conn.Open();
using (var tx = conn.BeginTransaction())
{
var version = MakeSureLastVersionMatches(name, expectedVersion, conn, tx);
const string txt =
@"INSERT INTO ES_Events2 (CustomerId, Name, Version, Data)
VALUES(:customerId, :name, :version, :data)";
using (var cmd = new NpgsqlCommand(txt, conn, tx))
{
cmd.Parameters.AddWithValue(":name", name);
cmd.Parameters.AddWithValue(":version", version+1);
cmd.Parameters.AddWithValue(":data", data);
cmd.Parameters.AddWithValue(":customerId", customerId);
cmd.ExecuteNonQuery();
}
tx.Commit();
}
}
}
示例7: SalvarGrupo
public void SalvarGrupo(GrupclienteDto entidade)
{
using (var conn = new NpgsqlConnection(Connectionstring))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
try
{
using (
var cmd =
new NpgsqlCommand(
"INSERT INTO grupcliente (grcl_nome, grcl_ativo,empr_codigo) values ('" + entidade.grcl_nome + "'," + entidade.grcl_ativo + ","+entidade.empr_codigo+")", conn,
trans))
{
cmd.ExecuteNonQuery();
trans.Commit();
}
}
catch (Exception)
{
trans.Rollback();
}
}
}
}
示例8: NpgsqlConnection
//Ska detta vara med?
/* public static List<string> GetGolfSpelarInfo(int GolfId)
{
List<string> medlemslista = new List<string>();
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[conString];
NpgsqlConnection conn = new NpgsqlConnection(settings.ConnectionString);
conn.Open();
NpgsqlCommand command2 = new NpgsqlCommand(@"SELECT *
FROM
golfspelare
WHERE
golf_id = :GolfId;
", conn);
command2.Parameters.Add(new NpgsqlParameter("GolfId", DbType.Int32));
command2.Parameters[0].Value = Convert.ToString(GolfId);
NpgsqlDataReader dr = command2.ExecuteReader();
while (dr.Read())
{
medlemslista.Add((string)dr["*"]);
}
conn.Close();
return medlemslista;
}*/
public static void AddSpelareTillTävling(string Fornamn, string Efternamn, string Tävlingsnamn)
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[conString];
NpgsqlConnection conn = new NpgsqlConnection(settings.ConnectionString);
NpgsqlTransaction trans = null;
try
{
conn.Open();
trans = conn.BeginTransaction();
NpgsqlCommand command3 = new NpgsqlCommand(@"SELECT golf_id
FROM golfspelare
WHERE fornamn = :Fornamn
AND efternamn =:Efternamn", conn);
command3.Parameters.Add(new NpgsqlParameter("Fornamn", DbType.String));
command3.Parameters[0].Value = Fornamn;
command3.Parameters.Add(new NpgsqlParameter("Efternamn", DbType.String));
command3.Parameters[1].Value = Efternamn;
command3.Transaction = trans;
int GolfId = (int)command3.ExecuteScalar();
//Tävlingsnamn är tomt när den anropas
NpgsqlCommand command4 = new NpgsqlCommand(@"SELECT id
FROM tavling
WHERE tavlingsnamn = :TävlingsNamn", conn);
command4.Parameters.Add(new NpgsqlParameter("TävlingsNamn", DbType.String));
command4.Parameters[0].Value = Tävlingsnamn;
command4.Transaction = trans;
int TävlingsID = (int)command4.ExecuteScalar();
/* NpgsqlCommand command4 = new NpgsqlCommand(@"SELECT id
FROM tavling
WHERE tavlingsnamn = :TävlingsNamn", conn);
command4.Parameters.Add(new NpgsqlParameter("tavlingsnamn", DbType.String));
command4.Parameters[0].Value = Tävlingsnamn;
command4.Transaction = trans;
int TävlingsID = (int)command4.ExecuteScalar(); */
NpgsqlCommand command5 = new NpgsqlCommand(@"INSERT INTO spelar_resultat (golf_id, tavlings_id)
VALUES (:GolfId, :TävlingsID)", conn);
command5.Parameters.Add(new NpgsqlParameter("GolfId", DbType.Int32));
command5.Parameters[0].Value = GolfId;
command5.Parameters.Add(new NpgsqlParameter("TävlingsID", DbType.Int32));
command5.Parameters[1].Value = TävlingsID;
command5.Transaction = trans;
int numberOfAffectedRows = command5.ExecuteNonQuery();
trans.Commit();
}
catch (NpgsqlException ex)
{
trans.Rollback();
}
finally
{
conn.Close();
}
}
示例9: PostgreSqlTransaction
public PostgreSqlTransaction(NpgsqlConnection connection)
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
_transaction = connection.BeginTransaction(IsolationLevel.Serializable);
}
示例10: DownloadQuestao
public void DownloadQuestao(Dominio.Questao questao)
{
Dominio.Configuracao configuracao = new Dominio.Configuracao();
string caminhoEntrada = System.IO.Path.Combine(configuracao.CaminhoSalvarSubmissoes, questao.ArquivoEntrada);
string caminhoSaida = System.IO.Path.Combine(configuracao.CaminhoSalvarSubmissoes, questao.ArquivoSaida);
NpgsqlConnection conexao = new NpgsqlConnection("Server=187.45.196.224;Database=bubblesort9;User ID=bubblesort9;Password=BSboca;");
NpgsqlTransaction transacao = null;
try
{
conexao.Open();
transacao = conexao.BeginTransaction();
LargeObjectManager lbm = new LargeObjectManager(conexao);
LargeObject lo = lbm.Open(questao.IdArquivoEntrada, LargeObjectManager.READ);
FileStream fsout = File.OpenWrite(caminhoEntrada);
byte[] buf = new byte[lo.Size()];
buf = lo.Read(lo.Size());
fsout.Write(buf, 0, (int)lo.Size());
fsout.Flush();
fsout.Close();
lo.Close();
lo = lbm.Open(questao.IdArquivoSaida, LargeObjectManager.READ);
fsout = File.OpenWrite(caminhoSaida);
byte[] buffer = new byte[lo.Size()];
buffer = lo.Read(lo.Size());
fsout.Write(buffer, 0, (int)lo.Size());
fsout.Flush();
fsout.Close();
lo.Close();
transacao.Commit();
}
catch
{
if (transacao != null)
transacao.Rollback();
throw;
}
finally
{
conexao.Close();
}
}
示例11: GetConnection
/// <summary>
/// Gets a fresh, open and ready-to-use connection wrapper
/// </summary>
public async Task<PostgresConnection> GetConnection()
{
var connection = new NpgsqlConnection(_connectionString);
await connection.OpenAsync();
var currentTransaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
return new PostgresConnection(connection, currentTransaction);
}
示例12: SaveExchangeRates
public static long SaveExchangeRates(string catalog, int officeId, string baseCurrency, IEnumerable<ExchangeRate> exchangeRates)
{
using (NpgsqlConnection connection = new NpgsqlConnection(DbConnection.GetConnectionString(catalog)))
{
connection.Open();
using (NpgsqlTransaction transaction = connection.BeginTransaction())
{
try
{
string sql = "UPDATE core.exchange_rates SET status = false WHERE [email protected]";
using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@OfficeId", officeId);
command.ExecuteNonQuery();
}
sql = "INSERT INTO core.exchange_rates(office_id, status) SELECT @OfficeId, true RETURNING exchange_rate_id;";
long exchangeRateId;
using (NpgsqlCommand er = new NpgsqlCommand(sql, connection))
{
er.Parameters.AddWithValue("@OfficeId", officeId);
exchangeRateId = Conversion.TryCastLong(er.ExecuteScalar());
}
foreach (ExchangeRate exchangeRate in exchangeRates)
{
sql =
"INSERT INTO core.exchange_rate_details(exchange_rate_id, local_currency_code, foreign_currency_code, unit, exchange_rate) " +
"SELECT @ExchangeRateId, @LocalCurrencyCode, @ForiegnCurrencyCode, 1, @ExchangeRate;";
using (NpgsqlCommand rate = new NpgsqlCommand(sql, connection))
{
rate.Parameters.AddWithValue("@ExchangeRateId", exchangeRateId);
rate.Parameters.AddWithValue("@LocalCurrencyCode", baseCurrency);
rate.Parameters.AddWithValue("@ForiegnCurrencyCode", exchangeRate.CurrencyCode);
rate.Parameters.AddWithValue("@ExchangeRate", exchangeRate.Rate);
rate.ExecuteNonQuery();
}
}
transaction.Commit();
return exchangeRateId;
}
catch (NpgsqlException ex)
{
Log.Warning(@"Could not update exchange rate. {Exception}", ex);
transaction.Rollback();
throw;
}
}
}
}
示例13: Connection
/// <summary>
/// Initializes a new instance of the <see cref="Connection" /> class.
/// </summary>
/// <param name="connectionInfo">The connection information.</param>
/// <param name="options">The options.</param>
public Connection(IConnectionInformation connectionInfo,
PostgreSqlMessageQueueTransportOptions options)
{
NpgsqlConnection = new NpgsqlConnection(connectionInfo.ConnectionString);
NpgsqlConnection.Open();
if (options.EnableHoldTransactionUntilMessageCommited)
{
NpgsqlTransaction = NpgsqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);
}
}
示例14: Setup
public void Setup()
{
OnSetupBeforeTransaction();
connection = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=sampledb;User Id=philipp;Password=test_pwd;");
connection.Open();
transaction = connection.BeginTransaction();
OnSetupInTransaction();
}
示例15: Save
public static bool Save(string catalog, int userId, string book, long id, Collection<Attachment> attachments)
{
const string sql =
"INSERT INTO core.attachments(user_id, resource, resource_key, resource_id, original_file_name, file_extension, file_path, comment) " +
"SELECT @UserId, core.attachment_lookup.resource, core.attachment_lookup.resource_key, @ResourceId, @OriginalFileName, @FileExtension, @FilePath, @Comment" +
" FROM core.attachment_lookup WHERE [email protected];";
using (NpgsqlConnection connection = new NpgsqlConnection(DbConnection.GetConnectionString(catalog)))
{
connection.Open();
using (NpgsqlTransaction transaction = connection.BeginTransaction())
{
if (attachments != null && attachments.Count > 0)
{
try
{
foreach (Attachment attachment in attachments)
{
using (NpgsqlCommand attachmentCommand = new NpgsqlCommand(sql, connection))
{
attachmentCommand.Parameters.AddWithValue("@UserId", userId);
attachmentCommand.Parameters.AddWithValue("@Book", book);
attachmentCommand.Parameters.AddWithValue("@ResourceId", id);
attachmentCommand.Parameters.AddWithValue("@OriginalFileName",
attachment.OriginalFileName);
attachmentCommand.Parameters.AddWithValue("@FileExtension",
Path.GetExtension(attachment.OriginalFileName));
attachmentCommand.Parameters.AddWithValue("@FilePath", attachment.FilePath);
attachmentCommand.Parameters.AddWithValue("@Comment", attachment.Comment);
attachmentCommand.ExecuteNonQuery();
}
}
transaction.Commit();
return true;
}
catch (NpgsqlException)
{
Log.Warning(
@"Could not insert attachment into database. Book: {Book}, Id: {Id}, Attachments: {Attachments}.\n{Sql}",
book, id, attachments, sql);
transaction.Rollback();
return false;
}
}
}
}
return false;
}