How to avoid every time initialization when value have greater than 0 - sql

I have a method that inserts a new record after checking whether it already exists or not.
Here is my method:
protected void btn_save_Click(object sender, EventArgs e)
{
string MobileNo = "";
string replaceValue = txt_mobile.Text.Replace(Environment.NewLine, "$");
string[] values = replaceValue.Split('$');
int uCnt = 0;
int sCnt = 0;
foreach (string item in values)
{
SaveRecord(item.Trim(),out MobileNo,out uCnt,out sCnt);
}
txt_mobile.Text = string.Empty;
if(uCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('Mobile No(s) : "+MobileNo.TrimEnd(',')+" Already Exist');", true);
}
if(sCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + sCnt + " Record(s) Inserted Successfully');", true);
}
Get_Data();
}
public void SaveRecord(string value, out string MobileNo, out int uCnt, out int sCnt)
{
uCnt = 0; //every time initialized to 0
sCnt = 0; //every time initialized to 0
MobileNo = "";
try
{
DataTable dt = new DataTable();
var dot = Regex.Match(value, #"\+?[0-9]{10}");
if (dot.Success)
{
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 0)
{
uCnt++;
MobileNo += value + ",";
}
else
{
string str1 = "INSERT INTO [dbo].[whitelistdata]([UserID],[SenderId],[KeywordID],[MobileNo])";
str1 += "VALUES (" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "," + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + ",1," + value + ")";
obj.Execute_Query(str1);
sCnt++;
}
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + ex.Message.ToString() + "');", true);
}
}
The problem is every time it's set to 0 when method has been called I want to prevent them when previous value is greater than 0.
Please help me guys..

Please first identify which combination check-in database.
if UserID AND SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if check the only UserID Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" +
Convert.ToInt32(ddl_users.SelectedValue.ToString()) +"'";
if UserID OR SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' OR [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if UserID AND SenderId AND MobileNo combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";

You need to use ref rather than out if you want to keep this design1. That means that the method can assume that the variables are already initialised and you're not forced to re-initialise them within the method:
public void SaveRecord(string value,out string MobileNo,ref int uCnt,ref int sCnt)
{
//uCnt = 0; //initialized by caller
//sCnt = 0; //initialized by caller
MobileNo = ""; //?
....
And at the call site:
SaveRecord(item.Trim(),out MobileNo,ref uCnt,ref sCnt);
You'll also want to do something about MobileNo too if you expect that to accumulate values rather than be over-written each time through the loop. Maybe make it a StringBuilder instead that you just pass normally (no ref or out) and let the SaveRecord method append to. out is definitely wrong for it.
1Many people would frown at a method that clearly wants to return values being declared void and making all returns via ref/out.
Something like:
public bool SaveRecord(string value)
{
...
Returning true for a new record, false for an existing record. I'd probably take out the exception handling from there and let the exception propagate higher before it's handled. Then the call site would be:
if(SaveRecord(item.Trim()))
{
sCnt++;
}
else
{
uCnt++;
MobileNo += item.Trim + ","
}

Related

How to run SQL query concurrently in one by one

I am developing one page like Daily SMS Log for retrieving info regarding SMS run in background. I have this SQL code:
First Section
--SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,
-- p.MobileNo,
-- p.Message,
-- p.CharCount,
-- p.strSenderID as Sender,
-- u.strUserName as UserId,
-- ds.strDR as DeliveryStatus,
-- ds.strDiscription as Original_DRStatus,
-- m.strMessageType as MessageType,
-- CONVERT(varchar(20) , p.ReceiveTime) as ReceiveTime,
-- CONVERT(varchar(20) , p.SendTime) as SendTime,
-- CONVERT(varchar(20) , p.DoneTime) as DoneTime,
-- p.RootId as Root,
-- sp.ProviderName,
-- (CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType
-- INTO #Results3
-- FROM NEWSMSLOG_2019_01..LOG_010119 p
-- INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid
-- left join senderids b on b.id = p.senderid
-- left join messagetype m on m.intcode = p.messagetype
-- left join smppproviders sp on sp.RootId=p.RootId
-- where 1=1
Second Section
-- SELECT *
-- FROM #Results3
-- SELECT
-- CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,
-- Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType
-- FROM #Results3
-- WHERE RowNumber BETWEEN('1' -1) * '109299' + 1 AND((('1' -1) * '109299' + 1) + '109299') - 1
Here when I uncomment the first line to where 1=1 then rows retrieved with success. And after that commenting up those line I uncomment second section then result shows bunch of rows. Now it's works fine in Management Studio.
Now I just want this result to grid view and here is my code:
protected void Get_Data()
{
try
{
string str = "";
DataTable dt = new DataTable();
str = "SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,";
str += "p.MobileNo,";
str += "p.Message,";
str += "p.CharCount,";
str += "p.strSenderID as Sender,";
str += "u.strUserName as UserId,";
str += "ds.strDR as DeliveryStatus,";
str += "ds.strDiscription as Original_DRStatus,";
str += "m.strMessageType as MessageType,";
str += "CONVERT(varchar(20), p.ReceiveTime) as ReceiveTime,";
str += "CONVERT(varchar(20), p.SendTime) as SendTime,";
str += "CONVERT(varchar(20), p.DoneTime) as DoneTime,";
str += "p.RootId as Root,";
str += "sp.ProviderName,";
str += "(CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType";
str += " INTO #Results3 ";
str += " FROM NEWSMSLOG_2019_01..LOG_010119 p ";
str += " INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid";
str += " left join senderids b on b.id = p.senderid";
str += " left join messagetype m on m.intcode = p.messagetype";
str += " left join smppproviders sp on sp.RootId = p.RootId";
str += " where 1 = 1 ";
if(ddl_users.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.userid = ' + CONVERT(varchar(5),"+ Convert.ToInt32(ddl_users.SelectedValue.ToString())+") + '";
}
if (ddl_sender.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.Senderid = '+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+'";
}
if(!string.IsNullOrEmpty(txt_mobileno.Text.Trim()))
{
str += " and p.MobileNo like '' % '"+txt_mobileno.Text.Trim()+"' % ''";
}
else
{
str += string.Empty;
}
if(ddl_delevery.SelectedItem.Text.ToString() =="All")
{
str += string.Empty;
}
else
{
str += " and p.Deliverystatus in ('+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+')'";
}
if(!string.IsNullOrEmpty(txt_CompaignName.Text.Trim()))
{
str += " and p.CampaignName like ''%'"+txt_CompaignName.Text.Trim()+"'%'' '";
}
else
{
str += string.Empty;
}
if(ddl_account.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.accounttype = '+CONVERT(varchar(2),"+Convert.ToInt32(ddl_account.SelectedValue.ToString())+")+'";
}
obj.Execute_Query(str);
string str1 = " SELECT * FROM #Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType";
str1 += " FROM #Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500' + 1) + '500') - 1";
str1 += " DROP TABLE #Results3";
dt = obj.Get_Data_Table_From_Str(str1);
ViewState["data"] = dt;
egrd.DataSource = dt;
egrd.DataBind();
ViewState["data"] = dt;
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
But I have no records found in grid view. What's problem is that?
--------------------------Updated--------------------------------------------
namespace BulkSMSSystem.App_Code.DAL
{
public class DAL_General : DataAccess
{
public DataTable Get_Data_Table_From_Str(string str, string cnn_type = "NEWBULKSMS")
{
DataTable dt = new DataTable();
GetConnection(cnn_type);
dt = GetDataTableByQuery(str);
return dt;
}
public void Execute_Query(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
GetExecuteNonQueryByStr(str);
}
public object Execute_Scalar(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
object rtn = GetScalarOfStr(str);
return rtn;
}
---------------------------Updated 2-------------------------------------
public DataTable GetDataTableByQuery(string str_query)
{
try
{
mobj_SqlCommand.CommandText = str_query;
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.Text;
//mobj_SqlConnection.Open();
SqlDataAdapter adpt = new SqlDataAdapter(mobj_SqlCommand);
DataTable ds = new DataTable();
adpt.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
}
}
public void GetExecuteNonQueryByStr(string query_str)
{
try
{
mobj_SqlCommand.CommandType = CommandType.Text;
mobj_SqlCommand.CommandText = query_str;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
CloseConnection();
}
}
--------------------------Updated 3-----------------------------------
protected void GetConnection(string cnn_db = "NEWBULKSMS")
{
try
{
string Cnn_Str = "";
string ServerName = "SHREE-PC";
string DBUserName = string.Empty;
string DBPassword = string.Empty;
DBPassword += "c#" + Convert.ToChar(49);
string Database = cnn_db;
Cnn_Str = "Data Source=" + ServerName + "; UID=" + DBUserName + "; PWD=" + DBPassword + "; Database=" + Database+";Integrated Security = True";
//Cnn_Str = "Data Source=SHREE-PC;Initial Catalog=Project_DB_MNG;Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
}
--------------------------Upadted 4--------------------------------------
As you are using temp table with one # sign it means that a temporary table will exists only during your session. However, if you create a temporary table with ##, then every user will be able to use that one, and none other can create a temp table with the same name, but it will be deleted when the owner session expired or disconnect.
So try to use in your code:
...
str += " INTO ##Results3 ";
...
And:
string str1 = " SELECT * FROM ##Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName
,AccountType";
str1 += " FROM ##Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500'
+ 1) + '500') - 1";
str1 += " DROP TABLE ##Results3";

MS SQL - Parameterized Query with Dynamic Number of Parameters

Right now I am using the following code to generate the WHERE clause in my query. I have a parameter for the search column (searchColumn) plus another parameter from a checked listbox that I use.
If no item is checked there is no WHERE clause at all.
Is it possible to put this into a parameterized query? For the second part there's most likely a way like searchColumn NOT IN ( ... ) where ... ist the data from an array. Though I am not sure how to handle the case when there's nothing checked at all.
Any thoughts or links on this?
strWhereClause = "";
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (" + searchColumn + " = '" + strSearch + "' "
+ "OR " + searchColumn + " = '" + strSearch + "') ";
}
else
{
strWhereClause += "OR (" searchColumn " = '" + strSearch + "' "
+ "OR " + searchColumn + " = '" + strSearch + "') ";
}
}
It sounds like you're just trying to dynamically build a parameterized query string using C#. You're halfway there with your code - my example below builds up a dictionary with paramter names and parameter values, which you can then use to create SqlParamters. One thing I'm not 100% sure about is where searchColumn is coming from - is this generated from user input? That could be dangerous, and parameterizing that would require using some dynamic SQL and probably some validation on your part.
strWhereClause = "";
Dictionary<string, string> sqlParams = new Dictionary<string, string>();
int i = 1;
string paramName= "#p" + i.ToString(); // first iteration: "#p1"
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (thisyear." + strKB + " = #p1 OR " + searchColumn + " = #p1) ";
sqlParams.Add(paramName, strSearch);
i = 2;
}
else
{
paramName = "#p" + i.ToString(); // "#p2", "#p3", etc.
strWhereClause += "OR (" searchColumn " = " + paramName + " "OR " + searchColumn + " = " + paramName + ") ";
sqlParams.Add(paramName, strSearch);
i++;
}
}
Then, when parameterizing your query, just loop through your dictionary.
if (sqlParams.Count != 0 && strWhereclause.Length != 0)
{
foreach(KeyValuePair<string, string> kvp in sqlParams)
{
command.Parameters.Add(new SqlParamter(kvp.Name, SqlDbType.VarChar) { Value = kvp.Value; });
}
}
For reference only:
string strWhereClause;
string searchColumn;
string strKB;
SqlCommand cmd = new SqlCommand();
private void button1_Click(object sender, EventArgs e)
{
strWhereClause = "";
int ParmCount = 0;
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
ParmCount += 1;
string strParamName = "#Param" + ParmCount.ToString(); //Param1→ParamN
cmd.Parameters.Add(strParamName, SqlDbType.NVarChar);
cmd.Parameters[strParamName].Value = strSearch;
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (thisyear." + strKB + " = " + strParamName + " "
+ "OR " + searchColumn + " = " + strParamName + ") ";
}
else
{
strWhereClause += "OR (thisyear." + strKB + " = " + strParamName + " "
+ "OR " + searchColumn + " = " + strParamName + ") ";
}
}
}

Can't add particular values to the database

So I'm currently having a problem where I can't seem to add values to my sql-database. I'm constantly getting sql error 104. Saying that some tokens are unknown.
try{
//The part below gets the employee-ID and the names of the skill I want to add to him/her.
String valdAnstalld = jComboBoxUppKompVal.getSelectedItem().toString();
String nyKomp = jComboBoxUppKID.getSelectedItem().toString();
String nyP = jComboBoxUppPF.getSelectedItem().toString();
String nyNiva = jComboBoxUppNiva.getSelectedItem().toString();
//This part takes the name of the skill, and gets its ID-number.
String KompID = "select kid from kompetensdoman where benamning = '" + nyKomp + "'";
String PlattID = "select pid from plattform where benamning = '" + nyP + "'";
//And finally this part is supposed to insert the ID-numbers into the "has_competance" table.
String sqlUppKomp = "insert into har_kompetens VALUES " + "(" + valdAnstalld + ", '"
+ KompID + "', '" + PlattID + "', '" + nyNiva + "' where aid = '" + valdAnstalld + "')";
idb.insert(sqlUppKomp);
JOptionPane.showMessageDialog(null, "Tillagd!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
uppdateraKomp();

Can not get data from column in table when value ""

I have a prolem in my project when i get value from column in table. I create database by c# code.
This is my code:
public static int typeTransactionIncome = 1; // thu
public static int typeTransactionExpense = 2; // chi
public static int typeTransactionDebt = 3; // nợ
public static int typeTransactionLoan = 4; // cho vay
public static string tableNameCategory = "categories";
private static string createTableTransactionString = "CREATE TABLE IF NOT EXISTS \"transactions\" " + "(\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
+ "\"name\" VARCHAR(140) ," + "\"amount\" FLOAT NOT NULL DEFAULT (0) ," + "\"type\" INTEGER NOT NULL ,"
+ "\"created_date\" DATETIME NOT NULL DEFAULT (CURRENT_DATE) ," + "\"displayed_date\" DATETIME NOT NULL DEFAULT (CURRENT_DATE) ,"
+ "\"cat_id\" INTEGER NOT NULL DEFAULT (0) ," + "\"with_person\" VARCHAR(50)," + "\"remind_date\" DATETIME,"
+ "\"remind_num\" INTEGER DEFAULT (0) ," + "\"note\" VARCHAR(140) ," + "\"status\" BOOL NOT NULL DEFAULT (0),"
+ "\"user_id\" INT NOT NULL DEFAULT (1))";
This is insert code: Insert some column, and there 2 insert menthod
public void insertNewIncome(string _name, string _note, double _amount, DateTime _displayedDate, int _catId, int _usertId)
{
try
{
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO " + tableNameTransaction + "(type, name, note, amount, displayed_date, cat_id, user_id) values (#type, #name, #note, #amount, #displayed_date, #cat_id, #user_id)";
cmd.Parameters.Add("#type", typeTransactionIncome);
cmd.Parameters.Add("#name", _name);
cmd.Parameters.Add("#note", _note);
cmd.Parameters.Add("#amount", _amount);
cmd.Parameters.Add("#displayed_date", _displayedDate);
cmd.Parameters.Add("#cat_id", _catId);
cmd.Parameters.Add("#user_id", _usertId);
cmd.ExecuteNonQuery();
//MessageBox.Show("income");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void insertNewDebt(string _debter, string _note, double _amount, DateTime _ngay_vay, DateTime _ngay_tra, int _user_id)
{
try
{
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO " + tableNameTransaction + "(type, with_person, note, amount, displayed_date, remind_date, user_id) VALUES (#type, #with_person, #note, #amount, #displayed_date, #remind_date, #user_id)";
cmd.Parameters.Add("#type", typeTransactionDebt);
cmd.Parameters.Add("#with_person", _debter);
cmd.Parameters.Add("#note", _note);
cmd.Parameters.Add("#amount", _amount);
cmd.Parameters.Add("#displayed_date", _ngay_tra);
cmd.Parameters.Add("#remind_date", _ngay_tra);
cmd.Parameters.Add("#user_id", _user_id);
cmd.ExecuteNonQuery();
//MessageBox.Show("debt");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
closeConnection();
}
}
I was insert some records to table by insertNewDebt and insertNewIncome menthod, it was ok, not any error.
This is menthod that get all record in table:
public List<ItemTransaction> loadTransactionAll(DateTime _start_date, DateTime _end_date, int _user_id)
{
List<ItemTransaction> li = new List<ItemTransaction>();
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT transactions.id AS master_id,transactions.name,transactions.amount,transactions.type,transactions.created_date, transactions.displayed_date,transactions.cat_id, transactions.with_person,transactions.remind_date,remind_num, transactions.note,transactions.status,transactions.user_id,categories.id,categories.name,categories.icon,categories.type,IFNULL(sub_amount,0) AS sub_amount "
+ "FROM transactions "
+ "LEFT JOIN categories ON transactions.cat_id = categories.id "
+ "LEFT JOIN ("
+ "SELECT sub_trans_id, IFNULL(SUM(sub_amount),0) AS sub_amount "
+ "FROM (SELECT trans_id AS sub_trans_id,SUM(amount) AS sub_amount "
+ "FROM sub_transactions "
+ "WHERE type = #type_income "
+ "GROUP BY sub_trans_id "
+ "UNION ALL SELECT trans_id AS sub_trans_id,SUM(amount) * -1 AS sub_amount "
+ "FROM sub_transactions "
+ "WHERE type = #type_expense GROUP BY sub_trans_id) GROUP BY sub_trans_id) ON sub_trans_id = master_id "
+ "WHERE (displayed_date BETWEEN #start_date AND #end_date) "
+ "AND transactions.user_id = #user_id "
+ "ORDER BY displayed_date DESC, transactions.type ASC, status ASC";
cmd.Parameters.Add("#type_income", DatabaseProccess.typeTransactionIncome);
cmd.Parameters.Add("#type_expense", DatabaseProccess.typeTransactionExpense);
cmd.Parameters.Add("#start_date", _start_date);
cmd.Parameters.Add("#end_date", _end_date);
cmd.Parameters.Add("#user_id", _user_id);
SqliteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ItemTransaction item = new ItemTransaction();
item.master_id = reader.GetInt32(0);
item.name = reader.GetString(1);
item.amount = reader.GetDouble(2);
item.type = reader.GetInt32(3);
item.created_date = reader.GetDateTime(4);
item.displayed_date = reader.GetDateTime(5);
item.cat_id = reader.GetInt32(6);
item.with_person = reader.GetString(7);
item.remind_date = reader.GetDateTime(8);
item.remind_num = reader.GetInt32(9);
item.note = reader[10].ToString();
item.status = reader.GetBoolean(11);
item.user_id = reader.GetInt32(12);
item.setCategory(reader.GetInt32(13), reader.GetString(14), reader.GetString(15), reader.GetInt32(16));
item.sub_amount = reader.GetDouble(17);
li.Add(item);
}
return li;
}
But when i execute insert:
insertNewIncome("", "note", "1000", DateTime.Today, 1, 1);
with 'name' field value = ""
I can not read 'name' field. Debug say:
view error screen shot here, please
And this is ItemTransaction class:
view ItemTransaction class here, please
I don't understand this error.
Please, thank
You're getting this error because name is NULL.
The following if statement would fix this:
if (reader(1) != null){
item.name = reader.GetString(1);
}
However if you're passing the value "", then this shouldn't be stored as NULL.
Check your database and see what the value is. Perhaps you have a trigger in place which updates "" to null.

Execute all Query or Nothing Should get executed

Well Try to Format Ques.I have set of Queries mentioned below.Now i want to have some functionality which can ensure either all query should execute or not even one(if some kind of error occur) i just want to maintain my database in proper state.
con.setAutoCommit(false);
String qry = "insert into tblAllotment(Employee_ID,Employee_Name,Area,Building_Name,Flat_Type,Flat_No,Date_Application,Date_Allotment,Admin_Code) values(" + id + ",'" + name[1] + "','" + area + "','" + flat[2] + "','" + flat[1] + "','" + flat[0] + "','" + dte + "','" + date + "'," + uid + ")";
String qry1 = "insert into tblFlat_Report(Flat_No,Area_Code,Employee_ID,Date_Allottment,Admin_Code)values('" + flat[0] + "'," + acode + "," + id + ",'" + date + "'," + uid + ")";
//String qry2="UPDATE tblUser_Report t1 JOIN (SELECT MAX(S_Date) s_date FROM tblUser_Report WHERE Employee_ID = "+id+") t2 ON t1.s_date = t2.s_date SET t1.Status = 'A', t1.S_Date ='"+date+"' WHERE t1.Employee_ID ="+id+"";
String qry2 = "insert into tblUser_Report(Employee_ID,Employee_Name,S_Date,Area,Status) values(" + id + ",'" + name[1] + "','" + date + "','" + area + "','A')";
String qry3 = "update tblFlat set Status ='A' where Flat_No='" + flat[0] + "' AND Area_Code=" + acode + " ";
String qry4 = "update tblUser set WL_Flag='N' where Employee_ID=" + id + "";
st = con.createStatement();
int i = st.executeUpdate(qry);
int j = st.executeUpdate(qry1);
int k = st.executeUpdate(qry2);
int l = st.executeUpdate(qry3);
int m = st.executeUpdate(qry4);
con.commit();
if (i != 0 & j != 0 & k != 0 & l != 0 & m != 0) {
Done = "Data Inserted Successfully...!!!";
} else {
System.out.println("Error Occured");
}
} catch (SQLException e) {
con.rollback();
System.out.println(e.getMessage());
}
}
Your database has to provide transactions. If you use MySQL, you cannot use a MyISAM database table, you have to use a InnoDB one (for example).
You begin a transaction at the start of your code, then check each result. If you get an error, you issue a rollback. If everything runs fine, you issue a commit at the end.
Your look should look like:
con.setAutoCommit(false); // at the beginning, to prevent auto committing at each insert/update/delete
// ... your updates, with error checking
con.commit(); // at the end, only if everything went fine.
In case of error, call con.rollback()
Wrap your queries in try catch. Add setAutoCommit(false) at the start of try and commit() at its end, add rollback() in catch block.
try {
conn.setAutoCommit(false);
// Execute queries
conn.commit();
}
catch (SQLException e) {
conn.rollback();
}