C#-Mysql Insert-Fatal error encountered during command execution - c#

I am trying to execute a INSERT statement on a mySQL DB in C#:
I read my other articles but could not find the right solution!!!!
This fails with the error: Fatal error encountered during command execution.
Any ideas on why this would fail?
string sqlQuery;
string sqlQuery2;
int countCat;
sqlQuery = "INSERT INTO xs_butiks (siteName,butikCode,butikCategory,butikTitle,butikLink,butikImgLink,butikHtmlCode,butikEndTime,butikStatus) VALUES (#SITE,#CODE,#CATEGORY,#TITLE,#LINK,#IMGLINK,#HTMLCODE,#ENDTIME,#STATUS)";
foreach (DataRow row in butiksTableTrendyol.Rows)
{
sqlQuery2 = "SELECT * FROM xs_butiks WHERE siteName='Trendyol' AND butikCode='" + row["butikCode"] + "'";
lock (dblock)
{
if (con.State != ConnectionState.Open) con.Open();
using (MySqlCommand cmd2 = new MySqlCommand(sqlQuery2, con))
{
countCat = Convert.ToInt32(cmd2.ExecuteScalar());
if (countCat <= 0)
{
lock (dblock)
{
//open connection
if (con.State != ConnectionState.Open) con.Open();
using (MySqlCommand cmd = new MySqlCommand(sqlQuery, con))
{
cmd.CommandText = sqlQuery;
cmd.Parameters.AddWithValue("#SITE", "Trendyol");
cmd.Parameters.AddWithValue("#CODE", row["butikCode"]);
cmd.Parameters.AddWithValue("#CATEGORY", row["butikCategory"]);
cmd.Parameters.AddWithValue("#TITLE", row["butikTitle"]);
cmd.Parameters.AddWithValue("#LINK", row["butikLink"]);
cmd.Parameters.AddWithValue("#IMGLINK", row["butikImgLink"]);
cmd.Parameters.AddWithValue("#HTMLCODE", string.Empty);
DateTime date = DateTime.Parse(row["butikEndTime"].ToString());
cmd.Parameters.AddWithValue("#ENDTIME", date);
cmd.Parameters.AddWithValue("#STATUS", "pending");
cmd.ExecuteNonQuery();
var ID = cmd.LastInsertedId;//get inserted ID
row["butikID"] = ID;//update dataTable
}
//close connection
if (con.State != ConnectionState.Closed) con.Close();
}
}
}
if (con.State != ConnectionState.Closed) con.Close();
}
/********************************************************************/
while (isLockedTrendyolButik) ;
Task.Factory.StartNew(() =>
{
GetTrendyolProducts(row, doc);
}
);
Interlocked.Increment(ref butikCounterTrendyol);//afzayesh yek vahedie globalCounter bad az har request movazi
if (butikCounterTrendyol == 10) isLockedTrendyolButik = true; //age globalCounter be 10 resid dg request ersal nemishe ta in 10ta tamom beshe. adade 10 ro mitonid be meghdare delkhah bar asase ghodrate server taghir dad. ta zamani ke timeOut ijad nashe in adad ghabele afzayeshe.
}

It's very possible its a bad datetime.
try this:
DateTime date;
bool goodDate = DateTime.TryParse(row["butikEndTime"].ToString(), out date);
if (goodDate)
cmd.Parameters.AddWithValue("#ENDTIME", date);
else
cmd.Parameters.AddWithValue("#ENDTIME", DateTime.MinValue);

Related

when trying to open a connection to phpmyadmin server the program freezes

I'm trying to get my application to work with the database which is online in a phpmyadmin sql server. when i start my application it needs to get the password from the database, but when it tries to open a connection the whole program just freezes and it stays like that for a long time. in each class in which i am using this i make a new connection i don't know if this could be a problem for this or not.
here underneath is the database class i am using for this.
class Database
{
private SqlConnection connection;
private string connectionstring = "Server=studmysql01.fhict.local;Uid=dbi413434;Database=dbi413434;Pwd=Koekjesdeeg;";
private string nfcId;
private int vak;
private int rij;
public Database()
{
connection = new SqlConnection(connectionstring);
}
public string GetPassword(string username)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT password FROM Login WHERE username = '" + username + "'", connection);
string checkPassWord = Convert.ToString(cmd.ExecuteScalar());
connection.Close();
return checkPassWord;
}
public void MakeAccount(string userName, string passWord)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO LOGIN (USERNAME, PASSWORD) VALUES (#USERNAME, #PASSWORD)";
comm.Parameters.AddWithValue("#USERNAME", userName);
comm.Parameters.AddWithValue("#PASSWORD", passWord);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("account is not made");
}
connection.Close();
}
public void Change_Info(double rate, int maximum_stay, int row, int line)
{
string command;
connection.Open();
SqlCommand comm = connection.CreateCommand();
if (rate == 0)
{
command = "UPDATE General SET Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
else if (maximum_stay == 0)
{
command = "UPDATE General SET Rate=#rate, Row=#row, Line=#line WHERE ID=1";
}
else if (row == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Line=#line WHERE ID=1";
}
else if (line == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row WHERE ID=1";
}
else
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
comm.CommandText = command;
comm.Parameters.AddWithValue("#rate", rate);
comm.Parameters.AddWithValue("#maximum_stay", maximum_stay);
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not updated in general");
}
connection.Close();
}
public void CheckForId(int id, int row, int line, bool taken, string target)
{
string queryUpdate = "UPDATE eventlog SET Rij=#row, Vak=#line, Beschikbaarheid=#taken, Parkeerdoel=#target WHERE ID=#id";
string queryInsert = "INSERT INTO eventlog (ID, Rij, Vak, Beschikbaarheid, Parkeerdoel) VALUES (#id, #row, #line, #taken, #target)";
string queryDelete = "DELETE * FROM eventlog WHERE id=#id";
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM eventlog WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", id);
string data = Convert.ToString(cmd.ExecuteScalar());
SqlCommand comm = connection.CreateCommand();
if (data == "")
{
comm.CommandText = queryInsert;
}
else if (Int32.Parse(data) == id)
{
comm.CommandText = queryUpdate;
}
else
{
comm.CommandText = queryDelete;
}
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
comm.Parameters.AddWithValue("#taken", taken);
comm.Parameters.AddWithValue("#target", target);
comm.Parameters.AddWithValue("#id", id);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not correctly inserted checkForid");
}
connection.Close();
}
public double GetRate()
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT Rate FROM General WHERE ID=1", connection);
double rate = Convert.ToDouble(cmd.ExecuteScalar());
connection.Close();
return rate;
}
public void SetId(int id, string nfcId, string kenteken, int row, int line, DateTime begintTijd)
{
if (row != -1 || line != -1)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO INCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", begintTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", row);
comm.Parameters.AddWithValue("#ParkeerVak", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not correctly inserted Setid");
}
connection.Close();
}
}
public void GetVisitorInformation(string kenteken)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT NfcId FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd2 = new SqlCommand("SELECT ParkeerVak FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd3 = new SqlCommand("SELECT ParkeerRij FROM INCHECK WHERE Kenteken=#kenteken", connection);
cmd.Parameters.AddWithValue("#kenteken", kenteken);
cmd2.Parameters.AddWithValue("#kenteken", kenteken);
cmd3.Parameters.AddWithValue("#kenteken", kenteken);
nfcId = Convert.ToString(cmd.ExecuteScalar());
vak = Convert.ToInt32(cmd2.ExecuteScalar());
rij = Convert.ToInt32(cmd3.ExecuteScalar());
connection.Close();
}
public void SetCheckOutId(int id, string kenteken, DateTime eindTijd)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO UITCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", eindTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", rij);
comm.Parameters.AddWithValue("#ParkeerVak", vak);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("checkoutid is not correctly inserted");
}
connection.Close();
}
public void SetParkingTargets(string target)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO ParkingTargets (Targets) VALUES (#Targets)";
comm.Parameters.AddWithValue("#Targets", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("parking targets are not set");
}
connection.Close();
}
public void DeleteParkingTarget(string target)
{
string queryDelete = "DELETE FROM ParkingTargets WHERE Targets=#target";
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = queryDelete;
comm.Parameters.AddWithValue("#target", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not deleted");
}
connection.Close();
}
public List<string> GetParkingTargets()
{
List<string> targets = new List<string>();
connection.Open();
SqlCommand cmd2 = new SqlCommand("SELECT COUNT(id) FROM ParkingTargets", connection);
int numberOfLines = Convert.ToInt32(cmd2.ExecuteScalar());
for (int i = 1; i <= numberOfLines; i++)
{
SqlCommand cmd = new SqlCommand("SELECT Targets FROM ParkingTargets WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", i);
targets.Add(Convert.ToString(cmd.ExecuteScalar()));
}
connection.Close();
return targets;
}
}

How to prevent 2 connection open in database?

I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.

c# database Select then insert. But the value is 0

I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}

Getting connection Open when Using a SqlConnection block within Another Block

In the project I call a method to query additional information with a SqlConnection block, but then I validate if exists in a second table using another sqlconnection block, but it is supposed to be disposed (closed) after getting back to the method InsertNewData, but when calling to Open the connection for the Insert, I'm getting the following message:
The connection was not closed. The connection's current state is open.
My code is like this:
public void InsertNewData(string operation)
{
DataTable dt = new DataTable();
try
{
if (operation!= string.Empty)
{
using (SqlConnection oconn = new SqlConnection(myDBone))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
string query = "SELECT * FROM operations "+
"WHERE idoper=#id";
oconn.Open();
cmd = new SqlCommand(query, oconn);
cmd.Parameters.Add(new SqlParameter("#id", operation.ToString()));
da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
if (dt.Rows.Count > 0)
{
using (SqlConnection con = new SqlConnection(myDBtwo))
{
SqlCommand com = new SqlCommand();
string query= "";
foreach (DataRow x in dt.Rows)
{
if (ValidateData(x) == false)
{
query= "INSERT INTO history(iddata,description, datehist ) "+
" VALUES(#id,#descrip,GETDATE())";
con.Open(); //Here throws the Exception error
com = new SqlCommand(query, con);
com.Parameters.Add(new SqlParameter("#id", x["idoper"].ToString()));
com.Parameters.Add(new SqlParameter("#descrip", x["description"] ));
com.ExecuteNonQuery();
}
}
}
}
}
}
catch (Exception x)
{
throw x;
}
}
public bool ValidateData(DataRow row)
{
bool exists= false;
string operation= row["idoper"].ToString();
string descrip= row["description"].ToString();
if (operation!= string.Empty && descrip!= string.Empty)
{
using (SqlConnection oconn = new SqlConnection(sqlrastreo))
{
SqlCommand cmd = new SqlCommand();
string query = "SELECT COUNT(*) FROM history "+
"WHERE iddata=#id AND description=#descrip";
oconn.Open();
cmd = new SqlCommand(query, oconn);
com.Parameters.Add(new SqlParameter("#id", operation));
com.Parameters.Add(new SqlParameter("#descrip", descrip));
int count = (int) cmd.ExecuteScalar();
if (count > 0)
exists= true;
}// Here it should be Disposed or closed the SqlConnection
}
return exists;
}
What I'm doing wrong, because it's suppose to be closed the other connection and the other hasn't been opened ? or Should I Still call the Close() method for each SqlConnection inside the block Using?
Updated:
I've changed to parameters for best reading code and recommendation syntax.
NOTE
The values and parameters aren't the real ones, my real table descriptions have about 8 fields, but I validate with just two parameters that aren't primary key, but considering that I can't edit the table properties (Have only reading permissions for that database).
Update 2:
Thanks to the recommendation of Sean Lange, it was better and so simple to use a Store Procedure (SP) to validate and insert at the same time, so I do it as follow in code of the process:
public void InsertNewData(string operation)
{
try
{
if(operation == string.Empty)
return;
using(SqlConnection con = new SqlConnection(myDBtwo))
{
con.Open();
var cmd = new SqlCommand("SP_InsertData", con);
cmd.Parameters.Add(new SqlParameter("#id", operation));
cmd.ExecuteNonQuery();
}
}
catch(Exception ex)
{ throw ex; }
}
And then in my SP I insert a select statement of the parameter, to avoid duplicates and also do it in One go:
CREATE PROCEDURE SP_InsertData #id VARCHAR(10)
AS
BEGIN
INSERT INTO History
SELECT O.idoper, O.description
FROM myDBone.dbo.operations O
LEFT JOIN History H
ON H.iddata = O.idoper AND H.description = O.description
WHERE O.idoper=#id AND H.iddata IS NULL
END
Thanks for your support, and hope it helps someone.
First your code is badly written,as they have suggested you don't need to validate,try catch will do it for you.second opening a connection inside a loop ( foreach in your case) will will result to trying to open already open connection. Example here you could do something like
query= "INSERT INTO history(iddata,description, datehist" VALUES(#id,#descrip,GETDATE())";
using (SqlConnection con = new SqlConnection(myDBtwo))
{
con.Open();
SqlCommand com = new SqlCommand(query,con);
foreach (DataRow x in dt.Rows)
{
com.Parameters.Add(new SqlParameter("#id", x["idoper"].ToString()));
com.Parameters.Add(new SqlParameter("#descrip", x["description"] ));
com.ExecuteNonQuery();
}
}
}

I have two input and one output parameter, how can I show data in grid view using a stored procedure?

Procedure name: AGENCY_STATE_REPORT
Input:
(frm_date date,
to_date1 date)
Output;
p_cur out SYS_REFCURSOR
My C# code:
public DataTable retdt1(string frmdate,string todate)
{
try
{
// Logfile("retdt", query);
con.Open();
if (con.State == ConnectionState.Open)
{
objCmd = new OracleCommand();
objCmd.CommandText = "AGENCY_STATE_REPORT ";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("#frm_date",OracleDbType.Date).Value=frmdate;
objCmd.Parameters.Add("to_date1", OracleDbType.Date).Value = todate;
objCmd.Parameters["# p_cur"].Direction = ParameterDirection.Output;
dap = new OracleDataAdapter(objCmd);
dt = new DataTable();
dap.Fill(dt);
if (dt.Rows.Count > 0)
{
return dt;
}
}
return null;
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
throw ex;
}
finally
{
if (con != null)
if (con.State != ConnectionState.Closed)
con.Close();
if (objCmd != null)
{
objCmd.Dispose();
dap.Dispose();
dt.Dispose();
}
}
}
I know it is wrong code, but how to send those two input parameters to the stored procedure?
Auto-populate
Binding GridView to dynamic DataTable
You can also lose the manual disposal by implementing "Using" blocks, example:-
using (var cnn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString))
{
cnn.Open();
using (var cmd = new SqlCommand(sql.ToString(), cnn))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
}

Categories