Running the same query causing error the second time - c#

I have a Data-table with all the mandatory fields which is required by select query in it. Now i am fetching data from 1st row of the data-table and running a select query (as given below). For the first time its working fine.
Now I am taking the 2nd row and giving all the mandatory fields (as i did for the first) and running the select query its giving error "insufficient permissions". When i am running both the select query (which are actually same but with different parameter) manually in Oracle SQL Developer its working fine.
Query1: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
Query2: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
To fetch data from database
public OracleDataReader ExecuteReader(string SelectQuery, string conString)
{
try
{
OpenDbConnection(conString);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = SelectQuery;
cmd.CommandType = System.Data.CommandType.Text;
OracleDataReader ora_dataReader = cmd.ExecuteReader();
return ora_dataReader;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
EDIT:
Forgot to mention that i am calling this funtion in another function as given below
public DataTable GetDataFromDB(string SelectQuery, string conString)
{
try
{
DataTable dt = new DataTable();
dt.Load(ExecuteReader(SelectQuery,conString));
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseDbConnection();
}
}

You need to open and close the connection after each query execution.
And also return the OracleDataReader after you have closed the connection or else it would lead to memory leak. If you return the OracleDataReader before you close connection, you would get the same error.
Try something like this:
public OracleDataReader ExecuteReader(string SelectQuery, string conString)
{
try
{
OpenDbConnection(conString);
OracleCommand cmd = new OracleCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = SelectQuery;
cmd.CommandType = System.Data.CommandType.Text;
OracleDataReader ora_dataReader = cmd.ExecuteReader();
}
catch (Exception ex)
{
Logging.LogMessage(Logging.LogLevel.Error, 0, "DAL", this.GetType().Name, ex.Message + " : " + ex.StackTrace);
throw ex;
}
finally
{
con.close();
con.Dispose();
}
return ora_dataReader;
}
More info in this reference: https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader(v=vs.110).aspx

You need to close the database connection and open it again before firing up your second query.
something like:
SqlConnection.Open();
And
SqlConnection.Close();

You need to ensure you're closing both the Connection and DataReader objects.
Try using the CommandBehavior argument in ExecuteReader, as it will close the connection automatically once you close the DataReader.
cmd.ExecuteReader(CommandBehavior.CloseConnection)

Related

Error when updating in database

I am getting error on updating database in C#. Here is the code:
string connectionstring = "server=AMAN;database=student;Integrated Security=True";
SqlConnection conn;
string Admission_no = txtAddmissionNo.Text;
SqlCommand cmd;
conn = new SqlConnection(connectionstring);
conn.Open();
string query = "update fees set prospectues_fee=#prospectues_fee, registration_fee=#registration_fee,admission_fee=#admission_fee ,security_money=#security_money,misslaneous_fee=#misslaneous_fee,development_fee=#development_fee,transport_fair=#transport_fair,computer_fee=#computer_fee ,activity=#activity,hostel_fee=#hostel_fee,dely_fine=#dely_fine,back_dues=#back_dues,tution_feemonth=#tution_feemonth ,tution_fee=#tution_fee,other_fee=#other_fee,total=#total,deposit=#deposit,dues=#dues where Admission_no=#Admission_no";
cmd=new SqlCommand(query,conn);
cmd.Parameters.AddWithValue("#Admission_no", Admission_no);
cmd.Parameters.AddWithValue("#prospectues_fee", prospectues_fee);
cmd.Parameters.AddWithValue("#registration_fee", registration_fee);
cmd.Parameters.AddWithValue("#admission_fee", admission_fee);
cmd.Parameters.AddWithValue("#security_money", security_money);
cmd.Parameters.AddWithValue("#misslaneous_fee", misslaneous_fee);
cmd.Parameters.AddWithValue("#development_fee", development_fee);
cmd.Parameters.AddWithValue("#transport_fair", transport_fair);
cmd.Parameters.AddWithValue("#computer_fee", computer_fee);
cmd.Parameters.AddWithValue("#activity", activity);
cmd.Parameters.AddWithValue("#hostel_fee", hostel_fee);
cmd.Parameters.AddWithValue("#dely_fine", dely_fine);
cmd.Parameters.AddWithValue("#back_dues", back_dues);
cmd.Parameters.AddWithValue("#tution_fee", tution_fee);
cmd.Parameters.AddWithValue("#other_fee", other_fee);
cmd.Parameters.AddWithValue("#total", total);
cmd.Parameters.AddWithValue("#tution_feemonth", tution_feemonth);
cmd.Parameters.AddWithValue("#deposit", deposit_fee);
cmd.Parameters.AddWithValue("#dues", dues);
cmd = new SqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Error is #prospectues_fee scalar must be declared, which I have already declared.
The error is simpler than I thought:
cmd = new SqlCommand(query, conn);
... // lots of code
cmd = new SqlCommand(query, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
You are creating a second command just prior to executing it; this second command has the text but no parameters. Remove this second new SqlCommand line.
This sounds like the dreaded null vs DBNull issue. null in a parameter means "don't send this". Which is really really silly, but there we are. Try with:
cmd.Parameters.AddWithValue("#prospectues_fee",
((object)prospectues_fee) ?? DBNull.Value);
now repeat for all of the parameters... or just add a method that loops over them and checks them:
static void FixTheCrazy(DbCommand command) {
foreach(DbParameter param in command.Parameters) {
if(param.Value == null) param.Value = DBNull.Value;
}
}
Alternatively, use a tool like dapper that will do it for you:
using(varconn = new SqlConnection(connectionstring))
{
conn.Execute(query, new {
Admission_no, prospectues_fee, registration_fee, ...
deposit_fee, dues });
}

Counting a specific number of records using MySqlDataReader

I have this code that counts the number of records with the same year and date. But when I run the application it doesn't work. Here is my code:
try
{
string query = "SELECT * FROM tblOrder WHERE dateTime_coded=#dateTimeNow";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#dateTimeNow", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM"));
MySqlDataReader dr = cmd.ExecuteReader();
MessageBox.Show("OK");
con.Open();
while (dr.Read())
{
count++;
}
dr.Close();
con.Close();
}
catch (Exception)
{
}
First you have an empty catch block which makes no sense
Atleast this would have been better
catch (Exception ex)
{
MessageBox(ex.Message);// you would know if in case it failed
}
Now the problem seems to be
MySqlDataReader dr = cmd.ExecuteReader();
MessageBox.Show("OK");
con.Open(); <--- opening after executing the reader !
you should try putting the connection in a using block
using(MySqlConnection con = new MySqlConnection())
{
//your stuff in here
}
Another observation
cmd.Parameters.AddWithValue("#dateTimeNow", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM"))
DateTime.Now is DateTime no need to Convert it again
A better approach to your problem is through ExecuteScalar (link for SqlServer but it is the same for MySql) and using the COUNT function
using(MySqlConnection con = new MySqlConnection("your_connection_string_here"))
{
con.Open();
string query = "SELECT COUNT(*) FROM tblOrder WHERE dateTime_coded=#dateTimeNow";
using(MySqlCommand cmd = new MySqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#dateTimeNow", DateTime.Now.ToString("yyyy-MM");
int count = (int)cmd.ExecuteScalar();
Console.WriteLine("There are " + count.ToString() + " records");
}
}
As you can see, I have removed the try/catch block that is useless here because you don't do anything with the exception. This will stop the program if your query contains a syntax error or you can't establish a connection with the server. So, if a try/catch is really needed depends on your requirements
(Added also the observation on the DateTime.Now from V4Vendetta)
You can SELECT COUNT(*) FROM ... and then use cmd.ExecuteScalar() to retrieve the count returned.

system.invalidoperationexception

I am trying to run this code
public Exception SetData(string Data , long NoOfColumnsAllowed)
{
try
{
con = new SqlCeConnection(conectionstring);
con.Open();
transaction = con.BeginTransaction();
com = new SqlCeCommand();
com.Transaction = transaction;
com.CommandText = "Select count(*) from [Copy]";
com.Connection = con;
sdr = com.ExecuteReader();
while (sdr.Read())
{
noOfColumns = sdr.GetInt32(0);
}
if (noOfColumns > NoOfColumnsAllowed)
{
long NoOfColumsToBeDeleted = noOfColumns - NoOfColumnsAllowed;
com.CommandText = "delete from [Copy] where Sno<=#sno";
com.Parameters.AddWithValue("#sno", NoOfColumsToBeDeleted);
com.ExecuteNonQuery();
}
com.CommandText = "Insert into [Copy] (Data) values (#data)";
com.Parameters.AddWithValue("#data", Data);
com.ExecuteNonQuery();
transaction.Commit();
con.Close();
return null;
}
catch (Exception ex)
{
try
{
transaction.Rollback();
}
catch (Exception)
{
}
con.Close();
return ex;
}
}
Exception Occur -
system.invalidoperationexception : The transaction can not be
committed if there is any opened cursor in the scope of this
transaction . Make sure all the data readers/ result sets are
explicitly closed before committing the change .
I am new with transaction and not able to find any valuable solution about opened cursor. Is there something wrong with code or i have to explicitly close the data reader if yes please tell me how ?
Just call sdr.Close(); right after the while loop since that's what error is complaining about.

How I can Insert Data in the MySQL Database?

I have a ASP.NET Application and a MySQL Database. I want write a Class to insert,delete and show the Data from the database. I have a Connection to the Database but I can't insert data in the database.
My Class insert method:
public string CreateEntry(string Connectionstring, string mitarbeiter)
{
connection = new MySqlConnection(Connectionstring);
try
{
var command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
return "Mitarbeiter wurde angelegt";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
connection.Close();
}
}
The Connectionstring is correct. I don't get a error but there is no data in the database.
My tablename: tb_mitarbeiter
columns: ID and Vorname
You should simply execute the command
....
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
command.ExecuteNonQuery();
....
I suppose that mitarbeiter is the real value that should be set in the database.
If this is the case remember to use parameters to insert/update your data
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES (?name)";
command.Parameters.AddWithValue("?name", mitarbeiter);
connection.Open();
command.ExecuteNonQuery();
You forgot to execute the command by calling command.ExecuteNonQuery(). This is how I would typically do it:
public string CreateEntry(string connectionString, string valueToInsert)
{
var stringToReturn = "";
try
{
using(var connection = new MySqlConnection(connectionString))
{
//Open connection
connection.Open();
//Compose query using sql parameters
var sqlCommand = "INSERT INTO table_name (field_name) VALUES (#valueToInsert)";
//Create mysql command and pass sql query
using(var command = new MySqlCommand(sqlCommand, connection))
{
command.Parameters.AddWithValue("#valueToInsert", valueToInsert);
command.ExecuteNonQuery();
}
stringToReturn ="Success Message";
}
}
catch(exception ex)
{
stringToReturn = "Error Message: " + ex.Message;
}
return stringToReturn;
}
There are a few key things to keep in mind:
Wrap disposable objects with a using. In the case of
MySqlConnection, it will properly close and dispose the connection
when its out of scope.
Use SQL parameters when passing values inside
your query. This will avoid SQL injection and its much more easier
to maintain.
Personally, I like to have one exit point in a
function. In this example, the "stringToReturn" variable holds the
value to return once the function is done executing both
successfully or in case of a failure.
To do a Insert / Update / Delete u should add
connection.Open();
command.ExecuteNonQuery();
For select ()to show data from database use:
connection.Open();
command.ExecuteReader();
{
string MyConnection2 = "datasource=localhost;port=3306;username=root;password=1234";
string Query = "insert into DBname.TableName(id,Name,First_Name,Age,Address) values('" +this.IdTextBox.Text+ "','" +this.NameTextBox.Text+ "','" +this.FirstnameTextBox.Text+ "','" +this.AgeTextBox.Text+ "','" +this.AddressTextBox.Text+ "');";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You are not executing the command use SqlCommand.ExecuteNonQuery
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
command.ExecuteNonQuery();
return "Mitarbeiter wurde angelegt";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
connection.Close();
}
You missed to write this:-
....
connection.Open();
command.ExecuteNonQuery();
....
You can also used Sql parameter to prevent Sql Injection
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = #"INSERT INTO `tb_mitarbeiter` (`Vorname`) VALUES (#tom)";
command.Parameters.AddWithValue("#tom", tom);
connection.Open();
command.ExecuteNonQuery();
return "Mitarbeiter wurde angelegt";
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
command.Dispose();
command.Close();
connection.Close();
}

MySqlCommand.ExecuteNonQuery fails

I am trying to execute an INSERT query in a mysql DB, but it doesn't happen anything except that the code executions stops and nothing gets inserted.
Here is the code (the connection is made at another point and is working):
query = string.Format("INSERT INTO users (username, settings) VALUES('{0}', '{1}')", userName, sw.ToString());
myCommand = new MySqlCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
If I step the code, it stops after executenonquery, so obvisously something is wrong there. God I hate that it doesn't throw an error at me :(
Have you checked the connection is actually open and tried executing the method by assigning the result to an int in a try catch block.
int result;
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
result = Convert.ToInt32(dbComm.ExecuteNonQuery());
}
catch (Exception ex)
{
logger.Error(ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}

Categories