Here i need to access the variable delval outside the for loop as in the code below
cmd_mail.Parameters.Add("#deleteusers", SqlDbType.NVarChar).Value = delval;
..How to do this..
Here is my code
for (int i = 0; i <= NoOfUsers - 1; i++) {
using (SqlConnection Conn = new SqlConnection(constr_str)) {
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = Conn;
Conn.Open();
cmd.CommandText = "Select top 1 Login_User_Name from Rode_Provisioning_User where RequestId=#RequestId and CustomerCode =#CustomerCode and disableflag=0 order by User_Count";
cmd.Parameters.Add("#CustomerCode", SqlDbType.VarChar).Value = CustomerCode;
cmd.Parameters.Add("#RequestId", SqlDbType.VarChar).Value = RequestId;
string Loginusername = cmd.ExecuteScalar();
Conn.Close();
string delval = "";
if (string.IsNullOrEmpty(delval)) {
delval = Loginusername;
} else {
delval = delval + "," + Loginusername;
}
}
}
}
if (flag == "Yes") {
string constr_dep = "server=" + _strServer + ";database=" + _strDatabase + ";uid=" + _strUserid + ";pwd=" + _strPassword + ";";
SqlConnection con_dep = new SqlConnection();
con_dep.ConnectionString = constr_dep;
SqlCommand cmd_mail = new SqlCommand("delete_user_mailsend_sp", con_dep);
cmd_mail.CommandType = CommandType.StoredProcedure;
cmd_mail.CommandTimeout = 0;
cmd_mail.Parameters.Add("#companycode", SqlDbType.NVarChar).Value = CustomerCode
cmd_mail.Parameters.Add("#deleteusers", SqlDbType.NVarChar).Value = delval;
try {
con_dep.Open();
cmd_mail.ExecuteNonQuery();
} catch (SqlException ee) {
VWLogger.LogMessage("Exception in delete_user_mailsend_sp:", TraceEventType.Critical);
VWLogger.LogMessage(ee, TraceEventType.Critical);
return ee.Message;
flag = ee.Errors(0).ToString();
}
con_dep.Close();
}
Any suggestion?
Define it outside the loop then, and it will be visible in both blocks, as well as outside.
As zerkms said, declare it outside the loop. See below.
string delval = "";
for (int i = 0; i <= NoOfUsers - 1; i++)
{
// your existing stuff
// ...
if (string.IsNullOrEmpty(delval))
{
delval = Loginusername;
}
else
{
delval = delval + "," + Loginusername;
}
}
if (flag == "Yes")
{
// your existing stuff
// ...
cmd_mail.Parameters.Add("#deleteusers", SqlDbType.NVarChar).Value = delval;
}
Related
I'm using Transactions on my Dao and in particular I'm using the TransactionScope object for the first time. But when I compile and start my procedure on my pc the method I wrote in will give me this error:
Connection must be valid and open to commit transaction
code:
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteReader();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
//cmd.Transaction = Transazione;
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteReader();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
You need to move scope.Complete(); within your connection using as it is being disposed before you are completing your scope. Also, change your calls to use ExecuteNonQuery as opposed to ExecuteReader, as you are opening a SqlDataReader and not disposing of it.
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
ok Ok i have inverted using connection with scope
And I opened the connection before scope and works !
I hope it is right, thank you !
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
using (TransactionScope scope = new TransactionScope())
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteNonQuery();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteNonQuery();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
i have a problem in fetching value from data gridview. In the same event i am able to fetch value from datagrid view1 but in same event i am not able to fetch the value from datagridview2. Help me with correction in following code.
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(path);
SqlConnection con1 = new SqlConnection(path);
con.Open();
string selectSql = "select * from textbooks where class='" + txt_class.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectSql, con);
string textname = "";
tempcnt.Text = "test";
string bookname = "";
double bookquantity = 0;
string textname1 = "";
string bookname1 = "";
double stockquantity1 = 0;
double bookquantity1 = 0;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
bookname = (reader["name"].ToString());
bookquantity = Convert.ToInt32(reader["quantity"]);
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
textname = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
if (textname == bookname)
{
bookquantity = bookquantity - 1;
temp_count.Text = bookquantity.ToString();
con1.Open();
string uquery = "update textbooks set quantity=" + bookquantity + " where name='" + bookname + "'";
SqlCommand cmd1 = new SqlCommand(uquery, con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
}
}
}
con.Close();
con.Open();
string selectSql2 = "select * from notebooks";
SqlCommand cmd2 = new SqlCommand(selectSql2, con);
tempcnt.Text = "test";
using (SqlDataReader reader1 = cmd2.ExecuteReader())
{
while (reader1.Read())
{
bookname1 = (reader1["name"].ToString());
stockquantity1 = Convert.ToInt32(reader1["quantity"]);
tempcnt.Text = bookname1;
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
textname1 = dataGridView2.Rows[i].Cells[0].Value as string;
string temp = Convert.ToString(dataGridView2.Rows[i].Cells[0].Value);
tempcnt.Text = temp;
if (temp == bookname1)
{
tempcnt.Text = "success";
}
}
}
}
con.Close();
}
I have this simple code C# and SQL Server database:
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
// here like cursor stop
cm2.ExecuteNonQuery();
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
I have run it but nothing happens on query execution I used MessageBox like that to identify the line that has the problem
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
MessageBox.Show("1");
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
MessageBox.Show("2");
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
MessageBox.Show("3");
// here cursor stops
cm2.ExecuteNonQuery();
// that messagebox isn't shown
MessageBox.Show("4");
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
Any help will be appreciated
You haven't opened your Connection. See below.
You should also use the using syntax to make use of IDisposable
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
var sqlCmdText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
try
{
using (var sqlConnection = new SqlConnection([YOUR CONNECTION STRING HERE]))
{
using (var sqlCommand = new SqlCommand(sqlCmdText, sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new DataException(ex.Message);
}
i got one thread reading on the database. When i click on the menustrip it shows an error "Database is locked." and it only happen sometimes. Any way to prevent the database lock? I have try WAL but its not working.
Reading:
private void checkPort(string ipIN, char[] input, string output)
{
try
{
bool building = false;
Thread beep = new Thread(Beep);
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string query = "select * from ALL_IO(nolock)";
using (SQLiteCommand cmd = new SQLiteCommand(query, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
int Contact;
while (dr.Read())
{
string _IP = dr.GetString(0);
string _IO_I = dr.GetString(1);
string _BuildingName = dr.GetString(4);
int IO_I = Convert.ToInt32(dr.GetString(1).Replace("DI ", ""));
if (dr.GetString(3) == "NC")
{
Contact = 1;
}
else
{
Contact = 0;
}
_tableName = dr.GetString(8);
string _name = dr.GetString(5);
var _active = dr.GetString(6);
var _status = dr.GetString(7);
if (_active == "Yes" && _status == "Enable")
{
//Some condition check here
}
}
catch { }
}
Writing:
void contexMenuuu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
data = "";
ToolStripItem item = e.ClickedItem;
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string sql = "select * from " + Properties.Settings.Default.TableName + "(nolock) where Name= '" + Properties.Settings.Default.LabelName.Replace(" DO", "") + "' ";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
_controllerIP = dr.GetString(0);
_IO = dr.GetString(1);
_IO_O = dr.GetString(2).Replace("DO ", "");
_Name = dr.GetString(4);
_Interval = Convert.ToInt32(dr.GetString(9));
}
}
}
}
if (item.Text == "Bypass Enable")
{
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
//c.DefaultTimeout = 2000;
c.Open();
string sql = "update ALL_IO SET Active='Yes', Status='Bypass' where ControllerIP='" + _controllerIP + "' and DI='" + _IO + "';";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
lock (lockobj)
{
//SQLiteConnection.ClearAllPools();
cmd.ExecuteNonQuery(); //Error occur here
}
}
}
}
Once the functionality is finished you must close the Database connect for avoid database lock issue. For executing the query you opened the database connection after that you didn't close it. so you need to close.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
This is my code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.Common;
public class General_function
{
internal System.Windows.Forms.DataGridView DG_ItemShow;
public static object Get_Single_Value(string SQLQuery)
{
try
{
object SingleValue = null;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = SQLQuery;
SingleValue = cmd.ExecuteScalar;
return SingleValue;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Get_Single_Value : " + ex.Message);
}
}
public static long get_Max_value(string tablename, string fieldname)
{
try
{
long maxvalue = 0;
DbConnection cn = database_Object.GetConnection(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
if (cn.State == ConnectionState.Closed)
{
cn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cn.Open();
}
cmd.Connection = cn;
cmd.CommandText = "select max(" + fieldname + ") From " + tablename;
string res = null;
res = cmd.ExecuteScalar.ToString;
if (string.IsNullOrEmpty(res))
{
maxvalue = 0;
}
else
{
maxvalue = long.Parse(res);
}
return maxvalue;
}
catch (Exception ex)
{
Interaction.MsgBox("Error in get_Max_value" + ex.Message);
}
}
public static int Save_Record(ArrayList Al, string TableName)
{
try
{
int Retval = 0;
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = ds.Tables(TableName);
ArrayList tal = new ArrayList();
foreach (DataColumn cl in dt.Columns)
{
tal.Add(cl.ColumnName);
}
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string n = null;
for (int i = 0; i <= tal.Count - 1; i++)
{
n = "#" + tal(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = n;
pa.Value = Al(i);
cmd1.Parameters.Add(pa);
}
n = "";
string v = "";
string sqlstr = "insert into " + TableName + " (";
for (int i = 0; i <= tal.Count - 1; i++)
{
n = n + "," + tal(i).ToString;
v = v + ",#" + tal(i).ToString;
}
n = Strings.Right(n, Strings.Len(n) - 1);
v = Strings.Right(v, Strings.Len(v) - 1);
sqlstr = sqlstr + n + ") values (" + v + ")";
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Save_Record : " + ex.Message);
}
}
public static int Delete_Record(ArrayList AlName, ArrayList AlValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "delete from " + TableName + " where ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + " And " + AlName(i).ToString + "=#" + AlName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 4);
sqlstr = sqlstr + v;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Delete_Record : " + ex.Message);
}
}
public static int Modify_Record(ArrayList AlName, ArrayList AlValue, ArrayList
AlPKName, ArrayList AlPKValue, string TableName)
{
try
{
int Retval = 0;
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
DbCommand cmd1 = default(DbCommand);
cmd1 = database_Object.GetCommand(database_Object.Provider);
cmd1.Connection = cnn;
string m = null;
//values parameters
for (int i = 0; i <= AlName.Count - 1; i++)
{
m = "#" + AlName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlValue(i);
cmd1.Parameters.Add(pa);
}
//primary key column parameters
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
m = "#" + AlPKName(i).ToString;
DbParameter pa = database_Object.GetParameter(database_Object.Provider);
pa.ParameterName = m;
pa.Value = AlPKValue(i);
cmd1.Parameters.Add(pa);
}
string sqlstr = "update " + TableName + " set ";
string v = "";
for (int i = 0; i <= AlName.Count - 1; i++)
{
v = v + "," + AlName(i).ToString + "=#" + AlName(i).ToString;
}
string w = "";
for (int i = 0; i <= AlPKName.Count - 1; i++)
{
w = w + " And " + AlPKName(i).ToString + "=#" + AlPKName(i).ToString;
}
v = Strings.Right(v, Strings.Len(v) - 1);
w = Strings.Right(w, Strings.Len(w) - 4);
sqlstr = sqlstr + v + " Where " + w;
cmd1.CommandText = sqlstr;
Retval = cmd1.ExecuteNonQuery;
return Retval;
}
catch (Exception ex)
{
Interaction.MsgBox("error in Modify_Record : " + ex.Message);
}
}
public static DataTable RecordSearch(string SqlString, string TableName)
{
try
{
DbConnection cnn = default(DbConnection);
cnn = database_Object.GetConnection(database_Object.Provider);
cnn.ConnectionString = My.Settings.Trasns_DataConnectionString;
cnn.Open();
Trasns_DataDataSet ds = new Trasns_DataDataSet();
DataTable dt = default(DataTable);
DbDataAdapter da = database_Object.GetAdapter(database_Object.Provider);
DbCommand cmd = database_Object.GetCommand(database_Object.Provider);
cmd.Connection = cnn;
cmd.CommandText = SqlString;
da.SelectCommand = cmd;
da.Fill(ds, TableName);
dt = ds.Tables(TableName);
cnn.Close();
cmd.Dispose();
da.Dispose();
cnn.Dispose();
return dt;
}
catch (Exception ex)
{
Interaction.MsgBox("error in RecordSearch : " + ex.Message);
}
}
}
How can I call the this class method from another page?
Using your static methods, you just call them by referencing the namespace:
object result = General_function.Get_Single_Value("select * from table");
as shown in code, you defined method as static so in order to invoke that method u can use,
var o = General_function.Get_Single_Value("your_parameter");
and
long lobj = General_function.get_Max_value("table_name","field_name");
and so on...