创建事务
Vertica 中的事务具有以下特性:原子、一致、隔离和持久。使用 Vertica ADO.NET 驱动程序连接到数据库时,连接处于自动提交模式,并且每个查询会在执行后提交。可以将多个语句收集到单个事务,然后使用单个事务同时提交这些语句。如果代码确定不应提交事务,您还可以选择在提交事务之前回退该事务。
这些事务使用 VerticaTransaction 对象,该对象是 DbTransaction 的实施。您必须将事务与 VerticaCommand 对象相关联。
以下代码使用显式事务将行逐个插入到 VMart 架构的表中。
要使用 ADO.NET 驱动程序在 Vertica 中创建事务:
-
使用连接创建命令对象。
VerticaCommand command = _conn.CreateCommand();
-
启动显式事务,并将命令与该事务相关联。
VerticaTransaction txn = _conn.BeginTransaction(); command.Connection = _conn; command.Transaction = txn;
-
执行各个 SQL 语句以添加行。
command.CommandText = "insert into product_dimension values( ... )"; command.ExecuteNonQuery(); command.CommandText = "insert into store_orders_fact values( ... )";
-
提交事务。
txn.Commit();
回退事务
如果代码检查到错误,则您可以捕获错误并回退整个事务。
VerticaTransaction txn = _conn.BeginTransaction();
VerticaCommand command = new
VerticaCommand("insert into product_dimension values( 838929, 5, 'New item 5' )", _conn);
// execute the insert
command.ExecuteNonQuery();
command.CommandText = "insert into product_dimension values( 838929, 6, 'New item 6' )";
// try insert and catch any errors
bool error = false;
try
{
command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
error = true;
}
if (error)
{
txn.Rollback();
Console.WriteLine("Errors. Rolling Back.");
}
else
{
txn.Commit();
Console.WriteLine("Queries Successful. Committing.");
}
提交和回退示例
以下示例详细介绍了如何在事务期间提交或回退查询。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Vertica.Data.VerticaClient;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
VerticaConnectionStringBuilder builder = new VerticaConnectionStringBuilder();
builder.Host = "192.168.1.10";
builder.Database = "VMart";
builder.User = "dbadmin";
VerticaConnection _conn = new VerticaConnection(builder.ToString());
_conn.Open();
bool error = false;
VerticaCommand command = _conn.CreateCommand();
VerticaCommand command2 = _conn.CreateCommand();
VerticaTransaction txn = _conn.BeginTransaction();
command.Connection = _conn;
command.Transaction = txn;
command.CommandText =
"insert into test values(1, 'test', 'test', 'test' )";
Console.WriteLine(command.CommandText);
try
{
command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
error = true;
}
command.CommandText =
"insert into test values(2, 'ear', 'eye', 'nose', 'extra' )";
Console.WriteLine(command.CommandText);
try
{
command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
error = true;
}
if (error)
{
txn.Rollback();
Console.WriteLine("Errors. Rolling Back.");
}
else
{
txn.Commit();
Console.WriteLine("Queries Successful. Committing.");
}
_conn.Close();
}
}
}
该示例将在控制台上显示以下输出:
insert into test values(1, 'test', 'test', 'test' )
insert into test values(2, 'ear', 'eye', 'nose', 'extra' )
[42601]ERROR: INSERT has more expressions than target columns
Errors. Rolling Back.