I have to insert data to 3 tables in my MySql let say it was table1, table2 and table3
my problem is sometimes insert query for table2 is executed twice and sometimes it's not executed
Here is my code :
string Query = #"insert into table1(SellCode, SellDate, SellType, Discount, BuyerCode)
values (#SellCode, #SellDate, #SellType, #Discount, #BuyerCode)";
using (MySqlConnection conExpDB = new MySqlConnection(ConString))
using (MySqlCommand cmdExpDB = new MySqlCommand(Query, conExpDB))
{
try
{
conExpDB.Open();
cmdExpDB.Parameters.AddWithValue("#SellCode", SellCode);
cmdExpDB.Parameters.AddWithValue("#SellDate", DateTime.Now);
cmdExpDB.Parameters.AddWithValue("#SellType", "Retail");
cmdExpDB.Parameters.AddWithValue("#Discount", txtDiscount.Text);
cmdExpDB.Parameters.AddWithValue("#BuyerCode", "1");
int rowsUpdated = cmdExpDB.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//end try
}//end using
string QueryB = #"insert into table2(PaymentCode, PaymentAmount,
SellCode, PaymentDate)
values (#PaymentCode, #PaymentAmount, #SellCode, #PaymentDate)";
using (MySqlConnection conExpDB = new MySqlConnection(ConString))
using (MySqlCommand cmdExpDB = new MySqlCommand(QueryB, conExpDB))
{
try
{
conExpDB.Open();
cmdExpDB.Parameters.AddWithValue("#PaymentCode", paymentcode);
cmdExpDB.Parameters.AddWithValue("#PaymentAmount", PaymentAmount);
cmdExpDB.Parameters.AddWithValue("#SellCode", SellCode);
cmdExpDB.Parameters.AddWithValue("#PaymentDate", DateTime.Now);
int rowsUpdated = cmdExpDB.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//end try
}//end using
foreach (DataGridViewRow row in GridView.Rows)
{
string QueryDetail = #"insert into table3(SellDetailCode, SellCode,
ItemCode, Qty,
Price)
values (#SellDetailCode, #SellCode, #ItemCode, #Qty,
#Price)";
using (MySqlConnection conExpDB = new MySqlConnection(ConString))
using (MySqlCommand cmdExpDB = new MySqlCommand(QueryDetail, conExpDB))
{
try
{
conExpDB.Open();
cmdExpDB.Parameters.AddWithValue("#SellDetailCode", SellDetailCode);
cmdExpDB.Parameters.AddWithValue("#SellCode", SellCode);
cmdExpDB.Parameters.AddWithValue("#ItemCode", ItemCode);
cmdExpDB.Parameters.AddWithValue("#Qty", Qty);
cmdExpDB.Parameters.AddWithValue("#Price", Price);
int rowsUpdated = cmdExpDB.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//end try
}//end using
}//end foreach
Is there any effective method to detect the queries are inserted twice or not executed? Or is there any problem with my queries?
Because it's happened very rare it's difficult for me fixed this error
Related
I'm calling stored procedure finish_record with 1 input parameter.
I read all related questions here for this topic but I didn't see mistake on my side...
But somewhere is it :-)
here procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `finish_record`(
IN recordId INT
)
BEGIN
UPDATE bnirolovani.record r INNER JOIN(
select Sum(SumError) as Total, count(RollID) as Rolls, sum(Lenght) as Lenght, sum(ExtraMeter) as ExtraMeter from bnirolovani.roll where RecordID=recordId)
i on r.RecordID = recordId SET r.SumError = i.Total, r.SumReels=i.Rolls,r.SumProduced=i.Lenght, r.SumExtraMeter=ExtraMeter;
UPDATE record r
INNER JOIN
(SELECT
SUM(Lenght) AS Total
FROM
bnirolovani.roll
WHERE
RecordID = recordId AND Quality = 0) i ON r.RecordID = recordId
SET
r.QualityE = i.Total;
UPDATE record r
INNER JOIN
(SELECT
SUM(Lenght) AS Total
FROM
bnirolovani.roll
WHERE
RecordID = recordId AND Quality = 1) i ON r.RecordID = recordId
SET
r.QualityII = i.Total;
UPDATE record r
SET
DateProducedF = NOW()
WHERE
r.RecordID = recordID;
END
and here my C# code
private void FinishRecord(int recordID)
{
try
{
string con = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (MySqlConnection conection = new MySqlConnection(con))
{
using (MySqlCommand cmd = new MySqlCommand("finish_record", conection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("recordId", MySqlDbType.Int32).Value=recordID;
conection.Open();
cmd.ExecuteNonQuery();
conection.Close();
}
}
}
catch (Exception ex)
{
throw;
}
Could someone help me where is mistake? I didn't see it :-(
THX
Solved
I replace C# code:
Add procedure call as simple CommandType=Command.Text instead of CommandType.Procedure
and works
private void FinishRecord(int recordID)
{
try
{
string con = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (MySqlConnection conection = new MySqlConnection(con))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Format("CALL finish_record({0})",recordID);
conection.Open();
cmd.ExecuteNonQuery();
conection.Close();
}
}
}
catch (Exception ex)
{
throw;
}
}
I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID
I wrote the transaction below in C# to insert data into 4 tables in Access. I deployed the application and when one of the users is inserting data, the insert is failing and the transaction isn't rolling back. I can tell that there's a failed insert because the ID column has skipped numbers when I do have a successful insert.
Would you be able to review my code to see what could be causing this? And secondly, how could I test for this prior to deploying? I can't seem to replicate the user error.
public static void InsertIndividualOwner(TaxInfo taxInfo, OwnerAddress address, OwnerEmailAddress emailAddress, IndividualOwner owner)
{
int ownerTaxInfoID = 0;
int addressRecord = 0;
int emailRecord = 0;
int ownerRecord = 0;
int specialistID = Properties.Settings.Default.DefaultUserId;
string insertTaxInfoString = "Insert Into TaxInfo (TIN, BIRT, CAL, PIN, DateAdded, ModifiedBySpecialistID) " +
"VALUES(#TIN, #BIRT, #CAL, #PIN, Date(), #ModifiedBySpecialistID)";
string insertAddressString = "Insert Into OwnerAddress (ownerTaxInfoID, streetAddress1, streetAddress2, city, stateID, zip, country, DateAdded, ModifiedBySpecialistID) " +
"Values(#ownerTaxInfoID, #streetAddress1, #streetAddress2, #city, #stateID, #zip, #country, Date(), #ModifiedBySpecialistID)";
string insertEmailAddressString = "Insert Into OwnerEmailAddress (ownerTaxInfoID, emailAddress, DateAdded, ModifiedBySpecialistID) Values (#ownerTaxInfoID,#emailAddress, Date(), #ModifiedBySpecialistID)";
string insertOwnerNameString = "Insert Into IndividualOwner (firstName, lastName, ownerTaxInfoID, DateAdded, ModifiedBySpecialistID) " +
"VALUES(#firstName, #lastName, #ownerTaxInfoID, Date(), #ModifiedBySpecialistID)";
string selectID = "Select ##Identity";
using (OleDbConnection connection = new OleDbConnection(Constants.ACCESSCONNECTIONSTRING))
{
connection.Open();
using (OleDbTransaction transaction = connection.BeginTransaction())
{
try
{
using (OleDbCommand insertTaxInfo = new OleDbCommand(insertTaxInfoString, connection, transaction))
{
insertTaxInfo.Parameters.AddWithValue("#TIN", taxInfo.tin);
insertTaxInfo.Parameters.AddWithValue("#BIRT", taxInfo.birtNo);
if (string.IsNullOrEmpty(taxInfo.cal))
{
insertTaxInfo.Parameters.AddWithValue("#CAL", DBNull.Value);
}
else insertTaxInfo.Parameters.AddWithValue("#CAL", taxInfo.cal);
if (string.IsNullOrEmpty(taxInfo.pin))
{
insertTaxInfo.Parameters.AddWithValue("#PIN", DBNull.Value);
}
else insertTaxInfo.Parameters.AddWithValue("#PIN", taxInfo.cal);
insertTaxInfo.Parameters.AddWithValue("#ModifiedBySpecialistID", specialistID);
try
{
insertTaxInfo.ExecuteNonQuery();
insertTaxInfo.CommandText = selectID;
ownerTaxInfoID = (int)insertTaxInfo.ExecuteScalar();
}
catch (OleDbException ex)
{
throw ex;
}
}
using (OleDbCommand insertAddress = new OleDbCommand(insertAddressString, connection, transaction))
{
insertAddress.Parameters.AddWithValue("#ownerTaxInfoID", ownerTaxInfoID);
insertAddress.Parameters.AddWithValue("#streetAddress1", address.streetAddress1);
if (address.streetAddress2 == "")
{
insertAddress.Parameters.AddWithValue("#streetAddress2", DBNull.Value);
}
else insertAddress.Parameters.AddWithValue("#streetAddress2", address.streetAddress2);
insertAddress.Parameters.AddWithValue("#city", address.city);
insertAddress.Parameters.AddWithValue("#stateID", address.stateID);
insertAddress.Parameters.AddWithValue("#zip", address.zip);
insertAddress.Parameters.AddWithValue("#country", address.country);
insertAddress.Parameters.AddWithValue("#ModifiedBySpecialistID", specialistID);
try
{
insertAddress.ExecuteNonQuery();
insertAddress.CommandText = selectID;
addressRecord = (int)insertAddress.ExecuteScalar();
}
catch (OleDbException ex)
{
throw ex;
}
}
using (OleDbCommand insertEmailAddress = new OleDbCommand(insertEmailAddressString, connection, transaction))
{
insertEmailAddress.Parameters.AddWithValue("#ownerTaxInfoID", ownerTaxInfoID);
insertEmailAddress.Parameters.AddWithValue("#emailAddress", emailAddress.emailAddress);
insertEmailAddress.Parameters.AddWithValue("#ModifiedBySpecialistID", specialistID);
try
{
insertEmailAddress.ExecuteNonQuery();
insertEmailAddress.CommandText = selectID;
emailRecord = (int)insertEmailAddress.ExecuteScalar();
}
catch (OleDbException ex)
{
throw ex;
}
}
using (OleDbCommand insertOwner = new OleDbCommand(insertOwnerNameString, connection, transaction))
{
insertOwner.Parameters.AddWithValue("#firstName", owner.firstName);
insertOwner.Parameters.AddWithValue("#lastName", owner.lastName);
insertOwner.Parameters.AddWithValue("#ownerTaxInfoID", ownerTaxInfoID);
insertOwner.Parameters.AddWithValue("#ModifiedBySpecialistID", specialistID);
try
{
insertOwner.ExecuteNonQuery();
insertOwner.CommandText = selectID;
ownerRecord = (int)insertOwner.ExecuteScalar();
}
catch (OleDbException ex)
{
throw ex;
}
}
transaction.Commit();
AddOwner?.Invoke();
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
}
I am inserting data in sql server 2008 R2 from web api. There are about 300 records that are inserted in 3 to 4 tables. First 20 to 30 records are easily inserted in few millisecond after that it will take few seconds to few minutes to insert records. The sql server is installed in Windows Server 2012 R2.
If I delete the same record after it is inserted and then again call the api to insert same data, it will just take 2 to 3 seconds to insert.
This is the api code
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ProductsApp.ApplicationLogics;
using System.Web.Http.Cors;
using Newtonsoft.Json;
namespace ProductsApp.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "POST")]
public class DataPostController : ApiController
{
[AcceptVerbs("POST")]
public string DataPost([FromBody] List<Models.ReadingData> model)
{
if (model == null)
{
return "Data not found!";
}
string sql, id1;
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["APIConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlTransaction tran = con.BeginTransaction())
{
foreach (var item in model)
{
sql = #"INSERT INTO TableA(Col1, Col2, Col3, Col4)
SELECT #Col1, #Col2, #Col3, #Col4;
SELECT SCOPE_IDENTITY();";
using (SqlCommand sqlCommand = new SqlCommand(sql, con, tran))
{
sqlCommand.Parameters.AddWithValue("#Col1", item.value1);
sqlCommand.Parameters.AddWithValue("#Col2", item.value2);
sqlCommand.Parameters.AddWithValue("#Col3", item.value3);
try
{
id1 = Convert.ToString(sqlCommand.ExecuteScalar());
if (item.amount > 0)
{
if (item.something != "0")
{
sql = #"INSERT INTO TableB(Col1, Col2, Col3)
SELECT #Col1, #Col2, #Col3;";
using (SqlCommand sqlCommand2 = new SqlCommand(sql, con, tran))
{
sqlCommand2.Parameters.AddWithValue("#Col1", id1);
sqlCommand2.Parameters.AddWithValue("#Col2", item.value5);
sqlCommand2.Parameters.AddWithValue("#FiscalYearId", item.value6);
try
{
sqlCommand2.ExecuteNonQuery();
}
catch (SqlException ex)
{
tran.Rollback();
return ex.Message;
}
}
}
}
if (item.advanceAmount > 0 || item.outstandingAmount > 0)
{
sql = #"UPDATE CustomersInfo SET AdvanceAmount=0, OutstandingAmount=0 WHERE CustomerId=#CustomerId;
UPDATE COAR SET IsClear=1 WHERE CustomerId=#CustomerId;
INSERT INTO COAR(FiscalYearId, CustomerId, EntryByUserId, OutstandingAmount, AdvanceAmount)
SELECT #FiscalYearId, #CustomerId, #EntryByUserId, #OutstandingAmount, #AdvanceAmount;";
}
else
{
sql = #"UPDATE CustomersInfo SET AdvanceAmount=0 WHERE CustomerId=#CustomerId;
UPDATE COAR SET IsClear=1 WHERE CustomerId=#CustomerId;";
}
using (SqlCommand sqlCommand2 = new SqlCommand(sql, con, tran))
{
sqlCommand2.Parameters.AddWithValue("#FiscalYearId", item.FiscalYearId);
sqlCommand2.Parameters.AddWithValue("#CustomerId", item.CustomerId);
sqlCommand2.Parameters.AddWithValue("#EntryByUserId", item.MeterReaderId);
sqlCommand2.Parameters.AddWithValue("#OutstandingAmount", item.outstandingAmount);
sqlCommand2.Parameters.AddWithValue("#AdvanceAmount", item.advanceAmount);
try
{
sqlCommand2.ExecuteNonQuery();
}
catch (SqlException ex)
{
tran.Rollback();
return ex.Message;
}
}
/*Insert Spot Fine (if any)*/
if (item.Fine > 0)
{
sql = #"INSERT INTO CreditSales(CreditSalesDateAD, CreditSalesDateBS, FiscalYearId,
CustomerId, ParticularsId, Amount, EntryByUserId, Status, MonthSN, MonthId)
SELECT #CreditSalesDateAD, #CreditSalesDateBS, #FiscalYearId,
#CustomerId, #ParticularsId, #Amount, #EntryByUserId, #Status, #MonthSN, #MonthId;";
using (SqlCommand sqlCommand4 = new SqlCommand(sql, con, tran))
{
sqlCommand4.Parameters.AddWithValue("CreditSalesDateAD", item.meterReadingDateAD);
sqlCommand4.Parameters.AddWithValue("CreditSalesDateBS", item.meterReadingDateBS);
sqlCommand4.Parameters.AddWithValue("FiscalYearId", item.FiscalYearId);
sqlCommand4.Parameters.AddWithValue("CustomerId", item.CustomerId);
sqlCommand4.Parameters.AddWithValue("ParticularsId", 5); //Always will be 5
sqlCommand4.Parameters.AddWithValue("Amount", item.Fine);
sqlCommand4.Parameters.AddWithValue("EntryByUserId", item.MeterReaderId);
sqlCommand4.Parameters.AddWithValue("Status", "0");
sqlCommand4.Parameters.AddWithValue("MonthSN", item.monthSN);
sqlCommand4.Parameters.AddWithValue("MonthId", item.MonthId);
try
{
sqlCommand4.ExecuteNonQuery();
}
catch (SqlException ex)
{
tran.Rollback();
return ex.Message;
}
}
}
/*If any tap repair complain*/
if (item.TapRepair == 1)
{
sql = #"INSERT INTO TapRepairs(ComplainDateAD, ComplainDateBS, FiscalYearId, CustomerId, ComplainTypeId,
RepairDateAD, RepairDateBS, RepairDescription, RepairByUserId)
SELECT #ComplainDateAD, #ComplainDateBS, #FiscalYearId, #CustomerId, #ComplainTypeId,
#RepairDateAD, #RepairDateBS, #RepairDescription, #RepairByUserId;";
using (SqlCommand sqlCommand5 = new SqlCommand(sql, con, tran))
{
sqlCommand5.Parameters.AddWithValue("#ComplainDateAD", item.meterReadingDateAD);
sqlCommand5.Parameters.AddWithValue("#ComplainDateBS", item.meterReadingDateBS);
sqlCommand5.Parameters.AddWithValue("#FiscalYearId", item.FiscalYearId);
sqlCommand5.Parameters.AddWithValue("#CustomerId", item.CustomerId);
sqlCommand5.Parameters.AddWithValue("#ComplainTypeId", item.Remarks);
sqlCommand5.Parameters.AddWithValue("#RepairDateAD", item.meterReadingDateAD);
sqlCommand5.Parameters.AddWithValue("#RepairDateBS", "");
sqlCommand5.Parameters.AddWithValue("#RepairDescription", "");
sqlCommand5.Parameters.AddWithValue("#RepairByUserId", item.MeterReaderId);
try
{
sqlCommand5.ExecuteNonQuery();
}
catch (SqlException ex)
{
tran.Rollback();
return ex.Message;
}
}
}
}
catch (SqlException ex)
{
if (ex.Message.Contains("MeterReadingEntries_FYID_MID_CID"))
{
//If meter reading entry already done
continue;
}
else
{
tran.Rollback();
return ex.Message;
}
}
}
}
tran.Commit();
con.Close();
con.Dispose();
}
}
return "ok";
}
}
}
Each table contains max 10 columns only.
What may be the cause? Is there anything wrong in the api? Why the insert is fast after the same record is deleted and re-inserted?
Update:
Profiler Image
Profiler Attached Image
In addition to creating stored procedures and sending a batch onto the stored procedure, I would definitely add that probably the execution plan for each query in each loop is different.
This has already been addressed on this post:
SQL Query slow in .NET application but instantaneous in SQL Server Management Studio
Look at the answer written by erikkallen
I have Sqlite method that makes SELECT query:
try {
myConn.Open();
using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
sqCommand.CommandText = sql;
SQLiteDataReader reader = sqCommand.ExecuteReader();
return reader.GetString(0);
}
} catch (Exception e) {
// do exception handling
}
I tried to get last inserted id:
sql = 'SELECT id FROM Pacients ORDER BY id DESC LIMIT 1';
I tried to di that like:
return reader.GetString(0);
it's throwing me down on exception "No current row"
After calling ExecuteReader you need to call Read to position on the first record of the dataset. Read returns true/false to inform you if there are records to read. So your code changes to
try {
myConn.Open();
using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
sqCommand.CommandText = sql;
SQLiteDataReader reader = sqCommand.ExecuteReader();
if(reader.Read())
return reader.GetString(0);
else
return ""; // or whatever you want to return if no records are present
}
} catch (Exception e) {
// do exception handling
}
Said that, remember that if you want to retrieve just one column from a single row like you have in your query then it is better to use ExecuteScalar instead of ExecuteReader
try {
myConn.Open();
using(SQLiteCommand sqCommand = new SQLiteCommand(sql, myConn)) {
sqCommand.CommandText = sql;
object result = sqCommand.ExecuteScalar();
return result != null ? result.ToString() : "";
}
} catch (Exception e) {
// do exception handling
}