Batch query exception - c#

When I execute the following code in C#, I can insert one record without issues. When I have two objects in my collection, I get the following error:
The variable name '#scoreboardId' has already been declared. Variable names must be unique within a query batch or stored procedure
Is there a way to work around this batch exception?
public void insertActiveMonitorsForScoreboard(SqlConnection dbConn, SqlTransaction dbTrans, int scoreboardId,
ObservableCollection<AvailableMonitorBo> availableMonitorsForAddOC)
{
using (SqlCommand dbCommand = new SqlCommand(CreateAndDisplaySQLStrings.INSERT_SCOREBOARD_MONITORS, dbConn))
{
dbCommand.Transaction = dbTrans;
foreach (AvailableMonitorBo bo in availableMonitorsForAddOC)
{
if (bo.IsActive)
{
dbCommand.Parameters.Add("scoreboardId", SqlDbType.Int).Value = scoreboardId;
dbCommand.Parameters.Add("availableMonitorId", SqlDbType.Int).Value = bo.AvailableMonitorId;
dbCommand.ExecuteNonQuery();
}
}
}
}

Try to add the parameters only once and subsequently only change their values.
public void insertActiveMonitorsForScoreboard(SqlConnection dbConn, SqlTransaction dbTrans, int scoreboardId,
ObservableCollection<AvailableMonitorBo> availableMonitorsForAddOC) {
using (SqlCommand dbCommand = new SqlCommand(CreateAndDisplaySQLStrings.INSERT_SCOREBOARD_MONITORS, dbConn)) {
dbCommand.Transaction = dbTrans;
dbCommand.Parameters.Add("scoreboardId", SqlDbType.Int);
dbCommand.Parameters.Add("availableMonitorId", SqlDbType.Int);
foreach (AvailableMonitorBo bo in availableMonitorsForAddOC) {
if (bo.IsActive) {
dbCommand.Parameters["scoreboardId"].Value = scoreboardId;
dbCommand.Parameters["availableMonitorId"].Value = bo.AvailableMonitorId;
dbCommand.ExecuteNonQuery();
}
}
}
}

Another approach is to put the SqlCommand inside your loop. This has the advantage that the SqlCommand is completely new for each loop, so nothing is carried over between iterations. This does not matter in this example, but in other cases it might.
public void insertActiveMonitorsForScoreboard(SqlConnection dbConn, SqlTransaction dbTrans, int scoreboardId,
ObservableCollection<AvailableMonitorBo> availableMonitorsForAddOC) {
foreach (AvailableMonitorBo bo in availableMonitorsForAddOC) {
if (bo.IsActive) {
using (SqlCommand dbCommand = new SqlCommand(CreateAndDisplaySQLStrings.INSERT_SCOREBOARD_MONITORS, dbConn)) {
dbCommand.Transaction = dbTrans;
dbCommand.Parameters.Add("scoreboardId", SqlDbType.Int).Value = scoreboardId;
dbCommand.Parameters.Add("availableMonitorId", SqlDbType.Int).Value = bo.AvailableMonitorId;
dbCommand.ExecuteNonQuery();
}
}
}
}

Related

Update using IDataParameter not working in Oracle

I have a C# abstract class for implementing database transactions that has both a SQL (System.Data.SqlClient) and Oracle (Oracle.ManagedDataAccess.Client) implementation.
public int ExecuteDML<T>(string sql, List<T> objects)
{
int cnt = 0;
using (IDbConnection conn = GetConnection())
{
using (IDbTransaction txn = conn.BeginTransaction())
{
using (IDbCommand cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = PrepSQL(sql);
cmd.Transaction = txn;
try
{
foreach (T obj in objects)
{
cmd.Parameters.Clear();
foreach (var kvp in GetDbParameters<T>(obj))
{
IDataParameter param = new DbParameter
{
ParameterName = kvp.Key,
Value = kvp.Value ?? DBNull.Value
};
cmd.Parameters.Add(param);
}
cnt += cmd.ExecuteNonQuery();
}
txn.Commit();
}
catch (Exception)
{
txn.Rollback();
throw;
}
}
}
}
return cnt;
}
I am able to execute INSERT, UPDATE and DELETE statements in both implementations. But when I run an UPDATE in the Oracle implementation, the record does not get updated in the database; ExecuteNonQuery returns 0. However, the same data/command in the SQL implementation works fine.
Why would the parameterized query not work for UPDATE, while INSERT and DELETE are fine?
Query
UPDATE CONFIG_PARAMS SET PARAM_VALUE = :ParamValue, LOAD_DATE = :LoadDate, UPDATED_BY = :UpdatedBy WHERE ACTION_NAME = :ActionName AND PARAM_NAME = :ParamName
Found solution in this post. BindByName setting needs to be set explicitly for Oracle, since the parameters were out of order.
I added this code after creating the IDbCommand
if (cmd is Oracle.ManagedDataAccess.Client.OracleCommand)
{
((Oracle.ManagedDataAccess.Client.OracleCommand)cmd).BindByName = true;
}

Cannot Use DbContext.Query inside a transaction

I am using EF6 to query a backend database. User can customize a temporary table and query the data from the temporary table. I am using
DataTable result = context.Query(queryStatement);
to get the result and it has been working fine.
Now the query is needed among a serious of other sqlcommand and a transaction is needed. So I have
public static DataTable GetData()
{
using (MyDbContext context = new MyDbContext())
using (DbContextTransaction tran = context.Database.BeginTransaction())
{
try
{
int rowAffected = context.Database.ExecuteSqlCommand(
"UPDATE [MyDb].dbo.[TableLocks] SET RefCount = RefCount + 1 WHERE TableName = 'TESTTABLE1'");
if (rowAffected != 1)
throw new Exception("Cannot find 'TestTable1'");
//The following line will raise an exception
DataTable result = context.Query("SELECT TOP 100 * FROM [MyDb].dbo.[TestTable1]");
//This line will work if I change it to
//context.Database.ExecuteSqlCommand("SELECT TOP 100 * FROM [MyDb].dbo.[TestTable1]");
//but I don't know how to get the result out of it.
context.Database.ExecuteSqlCommand(
"UPDATE [MyDb].dbo.[TableLocks] SET RefCount = RefCount - 1 WHERE TableName = 'TestTable1'");
tran.Commit();
return result;
}
catch (Exception ex)
{
tran.Rollback();
throw (ex);
}
}
}
But this throws an exception while executing context.Query
ExecuteReader requires the command to have a transaction when the connection
assigned to the command is in a pending local transaction. The Transaction
property of the command has not been initialized.
And when I read this article: https://learn.microsoft.com/en-us/ef/ef6/saving/transactions
It says:
Entity Framework does not wrap queries in a transaction.
Is it the reason cause this issue?
How can I use context.Query() inside a transaction?
What else I can use?
I tried all other method, none of them work - because the return datatype cannot be predicted before hand.
I just realized that, the Query method is defined in MyDbContext!
public DataTable Query(string sqlQuery)
{
DbProviderFactory dbFactory = DbProviderFactories.GetFactory(Database.Connection);
using (var cmd = dbFactory.CreateCommand())
{
cmd.Connection = Database.Connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlQuery;
using (DbDataAdapter adapter = dbFactory.CreateDataAdapter())
{
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}
May be you are missing this section -
you are free to execute database operations either directly on the
SqlConnection itself, or on the DbContext. All such operations are
executed within one transaction. You take responsibility for
committing or rolling back the transaction and for calling Dispose()
on it, as well as for closing and disposing the database connection
And then this codebase -
using (var conn = new SqlConnection("..."))
{
conn.Open();
using (var sqlTxn =
conn.BeginTransaction(System.Data.IsolationLevel.Snapshot))
{
try
{
var sqlCommand = new SqlCommand();
sqlCommand.Connection = conn;
sqlCommand.Transaction = sqlTxn;
sqlCommand.CommandText =
#"UPDATE Blogs SET Rating = 5" +
" WHERE Name LIKE '%Entity Framework%'";
sqlCommand.ExecuteNonQuery();
using (var context =
new BloggingContext(conn, contextOwnsConnection: false))
{
context.Database.UseTransaction(sqlTxn);
var query = context.Posts.Where(p => p.Blog.Rating >= 5);
foreach (var post in query)
{
post.Title += "[Cool Blog]";
}
context.SaveChanges();
}
sqlTxn.Commit();
}
catch (Exception)
{
sqlTxn.Rollback();
}
}
}
Specially this one -
context.Database.UseTransaction(sqlTxn);
Sorry guys, as mentioned above, I thought the Query method is from EF, but I examined the code and found it is actually coded by another developer, defined in class MyDbContext. Since this class is generated by EF, and I never think somebody have added a method.
It is
public DataTable Query(string sqlQuery)
{
DbProviderFactory dbFactory = DbProviderFactories.GetFactory(Database.Connection);
using (var cmd = dbFactory.CreateCommand())
{
cmd.Connection = Database.Connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlQuery;
//And I added this line, then problem solved.
if (Database.CurrentTransaction != null)
cmd.Transaction = Database.CurrentTransaction.UnderlyingTransaction;
using (DbDataAdapter adapter = dbFactory.CreateDataAdapter())
{
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}

Oracle table getting locked when trying to write out a clob

I'm writing out formatted text to a CLOB in Oracle table. Eventually as the process runs the table will get locked. When our DBA checks out the connections it appears that I've created multiple locks on the table and there are no other connections from other users. Any ideas on why the code below would eventually create locks on the table? It normally takes a few days of this code running a couple 100 times a day before the lock is created. There appear to be no hanging transactions.
public void Update_Html_Out(string key, string shortTitle, string htmlText)
{
byte[] newvalue = Encoding.Unicode.GetBytes(htmlText);
string sql = "UPDATE html_out SET short_title = :short_title, actual_text = :clob WHERE key = :key";
using (var conn = new OracleConnection(_connectionString))
using (var cmd = new OracleCommand(sql, conn))
{
conn.Open();
using (var transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted))
{
cmd.Transaction = transaction;
using (var clob = new OracleClob(conn))
{
clob.Write(newvalue, 0, newvalue.Length);
cmd.Parameters.Add("short_title", shortTitle);
cmd.Parameters.Add("clob", clob);
cmd.Parameters.Add("key", key);
cmd.ExecuteNonQuery();
transaction.Commit();
}
}
}
}
Try this code. Note, you need to save CLOB, not BLOB (you said it)
public void Update_Html_Out(string key, string shortTitle, string htmlText)
{
string sql = #"UPDATE html_out SET
short_title = :short_title,
actual_text = :clob
WHERE key = :key";
using (var conn = new OracleConnection(_connectionString))
{
conn.Open();
using (var transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted))
{
using (var cmd = new OracleCommand(sql, conn))
{
cmd.Transaction = transaction;
cmd.Parameters.Add("short_title", OracleDbType.Varchar2, shortTitle, ParameterDirection.Input);
cmd.Parameters.Add("clob", OracleDbType.Clob, htmlText, ParameterDirection.Input);
cmd.Parameters.Add("key", OracleDbType.Varchar2, key, ParameterDirection.Input);
cmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
}

C# Populate Object

I know people are going to scream that this topic is all over the internet. I know, I've read them. And I still don't understand it. I simply want to populate my object from the results of a stored procedure. Now this stored procedure takes at least 2 parameters - an action and what to find.
#Action
#customername
The #Action simply determine what the stored procedure needs to do and returns the results. So for example if I want to update a customer, I'd call the sp through my object:
public class Customer()
{
//properties
public int UpdateCustomer()
{
using (SQLConnection connection = new SqlConnection(Helper.CnnVal("DataConnection")))
{
SQLCommand = new SqlCommand(Helper.Procedure("Customer"), connection);
command.CommandType = CommandType.StoredProcedure;
SqlParameterCollection parameterCollection = command.Parameters;
parameterCollection.Add("#Action", SqlDbType.NVarChar, -1).Value = "Update"
//complete the rest of it....
}
}
}
This works well. So the problem arises when I simply want to populate the object with the results of the sp. In this case I would pass "Retrieve" as the #Action parameter and this.customer_name as the #customername parameter to the sp.
But how do I put the results from the stored procedure into the object?
I have this...
public void GetCustomer()
{
using (SQLConnection connection = new SqlConnection(Helper.CnnVal("DataConnection")))
{
var retrieval = new DynamicParameters();
retrieval.Add("#Action", "Retrieve");
retrieval.Add("#name", this.customer_Name);
connection.Open():
connection.Execute(Helper.Procedure("Customer"), retrieval, commandType: CommandType.StoredProcedure);
}
}
But I don't think it's working.
Back a long time ago I used to run a "fetch" for PHP when I needed to populate an object. Should I go back to this?
You need to execute a SqlReader on the command, Something like this:
using (var connection = new SqlConnection("Connection"))
using (var command = new SqlCommand("Retrieve", connection))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#Action", "Retrieve");
command.Parameters.AddWithValue("#name", this.customer_Name);
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var item = new YourClass();
// You can use GetX() methods to get the value of the fields
item.Name = reader.GetString("name");
// You can also access the fields by using bracket notation
item.Age = (int)reader["age"];
// Be careful of nullable fields though!
}
}
}
Using #Encrypt0r advice and guidance I got it working:
public void GetCustomer() {
using (SqlConnection connection = new SqlConnection(Helper.CnnVal("DataConnection"))) {
SqlCommand command = new SqlCommand(Helper.Procedure("Customer"), connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#Action", "Retrieve");
command.Parameters.AddWithValue("#name", this.customer_name);
connection.Open();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
this.tbl_id = (int)reader["tbl_id"];
this.customer_name = (string)reader["customer_name"];
this.customer_id = reader.GetInt32(customer_id);
this.customer_address = (string)reader["customer_address"];
this.customer_city = (string)reader["customer_city"];
this.customer_state = (string)reader["customer_state"];
this.customer_zip = reader.GetInt32(customer_zip);
}
}

MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll

I am trying to query the MySQL database from a c# application. Below is the code , here I am using parameterized query
public static void ValidateName(MySqlConnection conn,List<Employee> EmpList, string Group)
{
string selectQuery = "Select Name from Employee where Group = #Group AND #Name in (FirstName, LastName);";
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
for (int i = 0; i < EmpList.Count; i++)
{
cmd.Parameters.Add("#Group", MySqlDbType.VarChar).Value = Group;
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
var reader = cmd.ExecuteReader();
List<string> lineList = new List<string>();
while (reader.Read())
{
lineList.Add(reader.GetString(0));
}
if (lineList.Count <=0)
{
WriteValidationFailure(EmpList[i], "Failed");
}
}
}
But the above code is throwing error in below line saying
cmd.Parameters.Add("#Group", MySqlDbType.VarChar).Value = Group;
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException'
occurred in MySql.Data.dll' #Group has already been defined
This is happening because you are adding the same set of parameters in each iterations. You can either clear then in each iteration or else add them before starting the loop and change the value of existing parameter during each iteration. I think second option would be great. One more thing I have to specify here is about the reader, you have to use reader as an using variable so that each time it will get disposed at the end of the using block and your code works fine. Which means you can try something like this:
using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
{
cmd.Parameters.Add(new MySqlParameter("#Group", MySqlDbType.VarChar));
cmd.Parameters.Add(new MySqlParameter("#Name", MySqlDbType.VarChar));
for (int i = 0; i < EmpList.Count; i++)
{
cmd.Parameters["Group"].Value = group;
cmd.Parameters["Name"].Value = EmpList[i].Name;
// rest of code here
using (MySqlDataReader reader = cmd.ExecuteReader())
{
// Process reader operations
}
}
}

Categories