I want to read data from an oracle database and add that data in to a List. But when I run the application I'm getting the 'Invalid operation. The connection is closed.' error.
This is my code:
public class NewOtherCompanyMapper
{
OtherCompany om;
private Database db;
private DbCommand cmd;
private DbConnection con;
public NewOtherCompanyMapper(OtherCompany om_temp)
{
om = om_temp;
db = DatabaseFactory.CreateDatabase("NDA_generator");
}
public List<OtherCompany> getCompanyDetails()
{
List<OtherCompany> list = new List<OtherCompany>();
OtherCompany oc = new OtherCompany();
try
{
con = db.CreateConnection();
con.Open();
string query = "SELECT * FROM OtherCompanyData";
cmd = db.GetSqlStringCommand(query);
DbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
oc = new OtherCompany(reader["RegNumber"].ToString(), reader["ComName"].ToString(), reader["Country"].ToString(), reader["Address"].ToString(), reader["CoreBusi"].ToString());
list.Add(oc);
}
}
catch (Exception ex)
{
throw ex;
}
return list;
}
}
Can you please help me to solve this problem.
Try replacing this
cmd = db.GetSqlStringCommand(query);
with this:
cmd = con.CreateCommand();
cmd.CommandText = query;
Related
I placed my DB reader in a separate class file because I didn't want to keep rewriting it but I keep getting the error:
Object reference not set to an instance of an object. db was null
This is my DataReader:
namespace ProjectName
{
public class DBReader
{
string dsn = ConfigurationManager.ConnectionStrings["database"].ConnectionString.ToString();
public SqlDataReader SqlReader(string sql, string retDebug = "")
{
try
{
SqlConnection conn;
SqlCommand cmd;
SqlDataReader dr_user;
conn = new SqlConnection(dsn);
conn.Open();
try
{
cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 180;
dr_user = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return dr_user;
}
catch (SqlException ex)
{
retDebug = ex.Message;
return null;
}
conn.Close();
conn.Dispose();
}
catch (Exception ex)
{
retDebug = ex.Message;
}
return null;
}
}
}
This is where I'm catching the error...at
SqlDataReader reader = db.SqlReader(query, "");
in the code shown here:
<!DOCTYPE html>
<script runat="server">
ProjectName.DBReader db;
string projectName;
protected void Page_Load(object sender, EventArgs e)
{
LoadProjects();
}
public void LoadProjects()
{
string query = #"SELECT * FROM projects where project_type = 3;
SqlDataReader reader = db.SqlReader(query, "");
while (reader.Read())
{
//code does something here
}
}
</script>
I want to be able to reuse this because I know I will be using it many times in this project.
Any help/direction would be appreciated!
As others pointed out, like any class, you have to create a instance of that class before using.
HOWEVER, if you don't have any public vars (at least ones that will change with different users on the web site), then you can also have public members of that class, and create the class as static. (but, those public members MUST be the same for all logged on users)
So, your choice.
Always create an instance of the class before using.
eg this:
public void LoadProjects()
{
string query = #"SELECT * FROM projects where project_type = 3";
DBReader MyDB = new DBReader();
SqlDataReader reader = MyDB.SqlReader(query, "");
while (reader.Read())
{
//code does something here
}
}
Or, you can declare the class as static, like this:
(air code warning).
public static class DBReader
{
static readonly string dsn = ConfigurationManager.ConnectionStrings["database"].ConnectionString.ToString();
static public SqlDataReader SqlReader(string sql, string retDebug = "")
{
SqlDataReader dr_user = null;
using (SqlConnection conn = new SqlConnection(dsn))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 180;
conn.Open();
dr_user = cmd.ExecuteReader();
}
}
return dr_user;
}
}
So, now in code you don't have to create a instance.
eg:
public void LoadProjects()
{
string query = #"SELECT * FROM projects where project_type = 3";
SqlDataReader reader = MyCode.DBReader.SqlReader(query, "");
while (reader.Read())
{
//code does something here
}
}
I am working on a windows form project with a sql database I want to write some data but I couldn't. (the code doesn't give any error however no data is written.
The code below is the place where I want to write the data:
public static string stringConnection = #"Data Source=(localdb)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\POS.mdf; Integrated Security=True";
try
{
mySql = string.Empty;
mySql += "INSERT INTO Journal (Date) VALUES (" + "'"+ caisse + "'"+")" ;
connection.exsql(mySql);
}
catch(Exception exx)
{
MessageBox.Show(exx.ToString());
}
and here is the connection.exsql method:
public static void exsql(string sql)
{
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = default(SqlDataAdapter);
try
{
connection.ConnectionString = stringConnection;
connection.Open();
adapter = new SqlDataAdapter(sql, connection);
connection.Close();
//connection = null;
}
catch (Exception ex)
{
MessageBox.Show("Fatal sql error: " + ex.Message, "Sql Server connection failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You want to use the sqlCommand and execute .ExecuteNonQuery() to do an INSERT or UPDATE.
More info here.
Also, use parameterization (an example is shown in the link above), otherwise, you open yourself up to SQL injection and your code will fail if your variable contains a single quote.
Less code
private bool exsql(string query)
{
using(var conn = new SqlConnection(ConnectionString.path))
{
conn.Open();
using (var command = new SqlCommand(query, conn))
return command.ExecuteNonQuery() == 0 ? false : true;
}
}
SqlConnection con;
SqlCommand cmd;
public bool exsql(string query)
{
try {
con = null;
con = new SqlConnection(ConnectionString.path);
cmd = new SqlCommand(query, con);
con.Open();
var rowEffected = cmd.ExecuteNonQuery();
con.Close();
if(rowEffected>0)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception occurred !",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
You can execute your query by ExecuteNonQuery() function
I am having trouble with the following line:
MySqlDataReader DataReader = objDatabase.SetCommandType("GetRaceLevels").ExecuteReader();
It keeps returning the following error:
System.InvalidOperationException: 'Connection must be valid and open.'
private void RegisterForm_Load(object sender, EventArgs e)
{
HideMe();
MoveMe(-180);
MySqlConnection myConnection = objDatabase.GetConnection(); //must save the object based connection to a local variable for some reason.
myConnection.Open();
MySqlDataReader DataReader = objDatabase.SetCommandType("GetRaceLevels").ExecuteReader();
try
{
while (DataReader.Read())
{
cboRunnerTypes.Items.Add(DataReader[1]);
}
}
catch (Exception ex)
{
MessageBox.Show("Critical error!");
}
myConnection.Close();
}
I have tested the connection, it does work just fine, and it works during my login process.
The only other thing is this whole process utilises my clsDatabase class, that is where MySqlDataReader DataReader = objDatabase.SetCommandType("GetRaceLevels").ExecuteReader(); comes from.
This is the function on the clsDatabse class:
public MySqlCommand SetCommandType(string sProcedureName)
{
MySqlCommand myCommand = new MySqlCommand(sProcedureName, GetConnection()); //I think the problem is here, how am I fixing it though?
myCommand.CommandType = CommandType.StoredProcedure;
return myCommand;
}
I hope this all makes sense and I am not being extremely thick. Any help would be much appreciated! Thank you!
EDIT: The class:
class clsDatabase
{
private const string conString = "server = ; database = ; user = ; password = ; charset = utf8";
public MySqlConnection GetConnection()
{
MySqlConnection myConnection = new MySqlConnection(conString);
return myConnection;
}
public void EmailCommandCaller(MySqlCommand myCommand, string sEmail, string sContent)
{
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue(sEmail, sContent);
}
public void LoginCommandCaller(MySqlCommand myCommand, string sEmail, string sPassword, string sEmailContent, string sPasswordConetnt)
{
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue(sEmail, sEmailContent);
myCommand.Parameters.AddWithValue(sPassword, sPasswordConetnt);
}
public MySqlCommand SetCommandType(string sProcedureName)
{
MySqlCommand myCommand = new MySqlCommand(sProcedureName, GetConnection()); //I think the problem is here, how am I fixing it though?
myCommand.CommandType = CommandType.StoredProcedure;
return myCommand;
}
}
Everytime you call GetConnection() you're getting a brand new one. A new connection starts closed. Now, look at your SetCommandType method. It's instancianting a new MySqlCommand with a brand new connection, which is closed. You could open the connection in the method, but that is error prone, as you would end up with no means to close the connection afterward. Instead, instantiate the connection where you want to use it. Also, use using statements for better IDisposable handling.
private void RegisterForm_Load(object sender, EventArgs e)
{
HideMe();
MoveMe(-180);
using(MySqlConnection myConnection = new MySqlConnection(conString)){
myConnection.Open();
MySqlCommand myCommand = new MySqlCommand("GetRaceLevels", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
using(MySqlDataReader DataReader = myCommand.ExecuteReader()){
try
{
while (DataReader.Read())
{
cboRunnerTypes.Items.Add(DataReader[1]);
}
}
catch (Exception ex)
{
MessageBox.Show("Critical error!");
}
}
}
}
I´m asking how to connect two or more tables from an MS Access table into c# Windows forms?.
I get the error, that ue cant find the second table:
public partial class Form1 : Form
{
private OleDbConnection connection = new OleDbConnection();
private OleDbConnection connection2 = new OleDbConnection();
public Form1()
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\MitarbeiterDaten2.accdb;
Persist Security Info=False;";
connection2.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\be\Documents\DatenbankAbteilung.accdb;
Persist Security Info=False;";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader["ABTEILUNG"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
}
Anybody got an solution?
Its just about, how to connect two or more MS Access tables into C# Windows forms.
You can reuse the the objects, and can get data from various tables or databases, as :
private void Form1_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select ABTEILUNG from combo";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Abteilung.Items.Add(reader("ABTEILUNG").ToString());
}
reader.Close(); //' Always Close ther Reader. Don't left it open
connection2.Open();
command.Connection = connection2; //' Reusing Same Command Over New Connection
command.CommandText = "Select Field2 from Table2";
while (reader.Read)
{
if (!(Convert.IsDBNull(reader("Field2")))) //' Checking If Null Value is there
{
Abteilung.Items.Add(reader("Field2").ToString());
}
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
finally
{
connection.Close();
connection2.Close();
}
}
How about using using blocks to take care of the commands and connections and then using DataAdapter to get the job done easily. I use some code like this.
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(MDBConnection.ConnectionString))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT Column FROM Table1", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
using (OleDbCommand cmd = new OleDbCommand("SELECT AnotherColumn FROM Table2", con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
return ds;
I have written some C# to update a MySql table but I get an exception every time I call the method ExecuteNonQuery(). I have researched this on the web and every solution I find produces the same error. I have an open connection to the database and the update query to the database is written correctly. The code that I have so far come up with is :
public int executeUpdate()
{
int result = 0;
if (isConnected)
{
try
{
MySqlConnection cn = new MySqlConnection(connection.ConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
int numRowsUpdated = cmd.ExecuteNonQuery();
}
catch (MySqlException exSql)
{
Console.Error.WriteLine("Error - SafeMySql: SQL Exception: " + query);
Console.Error.WriteLine(exSql.StackTrace);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error - SafeMySql: Exception: " + query);
Console.Error.WriteLine(ex.StackTrace);
}
}
else
Console.Error.WriteLine("Error - SafeMySql: executeQuery failed. Not connected to DB");
}
Change your try section to the code below:
try
{
using(MySqlConnection cn = new MySqlConnection(connection.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cn;
cmd.CommandText = "UPDATE test SET status_id = 1 WHERE test_id = 1";
cn.Open();
int numRowsUpdated = cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
The connection must be opened before you execute a command. In the example above the command object will immediately be disposed and the connection object will implcitly be closed and disposed when you leave the using section.
I don't see the connection being opened.
Here is an example from MSDN: even inside a using block, they open the connection explicitly
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Edit: The principle is the same for MySQL as it is for SQL Server:
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}