Here is my database connection class.I want to access 'oracleCommand' object reference from another class.
public class DBConnection
{
//public OracleCommand oracleCommand;
public string cmd = "";
public void makeConnection()
{
//Opening connection
string connectionString = "XXXX";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
OracleCommand oracleCommand = con.CreateCommand();
cmd = oracleCommand.CommandText;
//Clossing resources
con.Close();
oracleCommand.Dispose();
}
Then I want to execute the following query.
dbConnection.cmd = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
OracleDataReader Reader = dbConnection.oracleCommand.ExecuteReader();
Reader.Read();
But 'dbConnection.oracleCommand.ExecuteReader()' does not hit when debugging. Does anyone has an idea?
You´re hiding the member oracleCommand by a variable with the same name that exists within the makeConnection-method. Omit the declaration in your method:
public class DBConnection
{
public OracleCommand oracleCommand;
public string cmd = "";
public void makeConnection()
{
//Opening connection
string connectionString = "XXXX";
OracleConnection con = new OracleConnection();
con.ConnectionString = connectionString;
con.Open();
this.oracleCommand = con.CreateCommand(); // here
cmd = oracleCommand.CommandText;
//Clossing resources
con.Close();
oracleCommand.Dispose();
}
However that won´t help you much as you can´t do anything with the command, because yo dispose it once makeConnection has run.
Furthermore it´s a bad idea to even expose a command to the outside. You should instead expose the connection and create a new command for every statement to be executed on the db:
public class DBConnection
{
public OracleConnection { get; private set; }
public string cmd = "";
public void makeConnection()
{
//Opening connection
string connectionString = "XXXX";
this.Connection = new OracleConnection();
this.Connection.ConnectionString = connectionString;
con.Open();
}
Now create a second method that executes your query and returns its results:
public int CountPendingElements()
{
using(var cmd = this.Connection.CreateCommand())
{
cmd.CommandText = "SELECT COUNT(JOB_ID) FROM EmployeeTable WHERE STATUS='Pending'";
OracleDataReader Reader = cmd.ExecuteReader();
Reader.Read();
return reader.GetInt32(0);
}
}
The using-statement ensures that even in case of an exception within the code-block the command is disposed.
As an aside your class should implement IDisposable to dispose its underlying connection when you´re done with it.
Related
I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}
I'm beginner working with .NET and Mysql Connection.
To avoid misunderstanding about Connection pool for .NET I want to ask some my question.
Here is simple my code
class Program
{
static void Main(string[] args)
{
string connectionSetting = "Data Source=127.0.0.1;Database=my_table; User Id=root;Password=root" + ";charset=euckr";
MySqlConnection con = new MySqlConnection(connectionSetting);
con.Open();
MySqlCommand command = new MySqlCommand("insert into log(strLog) values('log1')", con);
command.ExecuteNonQuery();
con.Close();
}
}
I've been trying to how to make connection instance for mysql-server, the answer was singleton, But I found many post in StackOverflow and Some answers say Don't share MySql Connection instance and that's all i have to do.
My question is "Who is controlling Connection Pool?"
In the above code, there is no code that relates to controlling the connection pool such as the GetPool, PutPool and so on calls. So I thought database connection pool is controlled in mysql-server side and there is not any other jobs on the .NET side. Is my understanding correct?
If my thought is right, I'll use the following codes.
class dbcp
{
public const string m_ConnectionString = "Data Source=127.0.0.1;Database=my_table; User Id=root;Password=root" + ";charset=euckr";
public MySqlConnection connection;
public dbcp() { }
public void QueryLog(string log)
{
connection = new MySqlConnection(m_ConnectionString);
connection.Open();
string strSQL = "insert into log(strLog) values('log1')";
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
}
class SomeClassA
{
public dbcp dbHandler;
}
class SomeClassB
{
public dbcp dbHandler;
}
class Program
{
static void Main(string[] args)
{
string connectionSetting = "Data Source=127.0.0.1;Database=gw_ocpp_server; User Id=root;Password=root" + ";charset=euckr";
MySqlConnection con = new MySqlConnection(connectionSetting);
con.Open();
MySqlCommand command = new MySqlCommand("insert into log(strLog) values('log1')", con);
command.ExecuteNonQuery();
con.Close();
}
}
Connection pooling is a technique of creating and managing a pool of connections:
Here's the additional info about connection pooling
I can't find a solution for the following:
Code:
class ApiData
{ SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\Users\Peter\Documents \db.sdf;");
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
public string code()
{
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText ="SELECT code FROM Charakter WHERE id=1";
rdr = cmd.ExecuteReader();
rdr.Read();
string selected = rdr.GetString(0);
conn.Close();
return (selected);
}
class Data{
ApiData g= new ApiData();
string vode = **g.code();**
}
Error:
A field initializer cannot reference the non-static field, method, or property
The initial values for fields need to use constants, static fields/methods/properties, or new instances. Instead, set it in your constructor:
class Data
{
ApiData g;
string vode;
public Data()
{
g = new ApiData();
vode = g.code();
}
}
Try making the field static which was giving this issue
//INITIALLY this field was non-static
//public string ConnectionString = "Data Source=ServerName;Initial Catalog=DBname;User Id=user_id;Password=password";
//Make this field static
public static string ConnectionString = "Data Source=ServerName;Initial Catalog=DBname;User Id=user_id;Password=password";
static SqlConnection sqlConnection = new SqlConnection(ConnectionString);
Hope this helps...
I have the following classes:
private static readonly string ConnectionString = "Dummy";
public static SqlConnection GetConnection()
{
SqlConnection Connection = new SqlConnection(ConnectionString);
return Connection;
}
public static SqlDataAdapter GetDataAdapter(string Query)
{
SqlDataAdapter Adapt = new SqlDataAdapter(Query, GetConnection());
return Adapt;
}
How do I dispose the SqlConnection object that is instantiated when GetConnection() is passed as parameter in my SqlDataAdapter constructor?
Will it get disposed automatically when I dispose my Adapt object in the method that called GetDataAdapter()?
If it's not possible to dispose it, how do you suggest to proceed?
Thanks for any help.
Description
If you dispose your SqlDataAdapter it does not dispose the SqlConnection too because its not clear if you want to use the connection again. You have to change your design to get this done.
I suggest to pass the SqlConnection to the GetDataAdapter function.
Sample
static void Main(string[] args)
{
using (SqlConnection connection = GetConnection())
{
using (SqlDataAdapter adapter = GetDataAdapter("YourQuery", connection))
{
}
// SqlDataAdapter is disposed
}
// SqlConnection is disposed
}
private static readonly string ConnectionString = "Dummy";
public static SqlConnection GetConnection()
{
SqlConnection Connection = new SqlConnection(ConnectionString);
return Connection;
}
public static SqlDataAdapter GetDataAdapter(string Query, SqlConnection connection)
{
SqlDataAdapter Adapt = new SqlDataAdapter(Query, connection);
return Adapt;
}
No, the adapter does not dipose the connection. You should change it to this at least:
public static SqlDataAdapter GetDataAdapter(SqlConnection connection, string Query)
{
SqlDataAdapter Adapt = new SqlDataAdapter(Query);
Adapt.Connection = connection;
return Adapt;
}
and use it like this
using (var connection = GetConnection())
using (var adapter = GetAdapter(connection, query))
{
// do stuff
}
This way you are also more flexible by being able to pass some other connection in - in case you need it for some exceptional circustances.
I have a simple two-field form that stores its data in the database. For some reason, it isn't working. I have verified that the connection string works, as it is used in another project I made.
I didn't include the beginning of the first class or its page load.
Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string Name = txtName.Text;
string Description = txtSpecial.Text;
string method = string.Format(
"INSERT INTO RbSpecials (Name,Description,Active) VALUES ('{0}','{1}','1')",
Name,
Description);
RbConfiguration mySql = new RbConfiguration();
try
{
mySql.Sql_Connection(method);
}
catch
{
}
}
}
public class RbConfiguration
{
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
public void Sql_Connection(string queryString)
{
SqlConnection conn = new SqlConnection(DbConnectionString);
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
conn.Close();
}
}
You never execute your SQL command:
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
And your connection string is wrong (ditch the double quotes):
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
Well without knowing the error, I'll give it a shot anyway.
string DbConnectionString = "System.Configuration.ConfigurationManager.ConnectionStrings['RBConnectionString'].ConnectionString";
Should be
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
And as Adam says, you never actually execute your Query.
The Sql_Connection-method, only opens a connection, and then closes it again, without actually doing anything.
Try this instead:
public void Sql_Connection(string queryString)
{
using( SqlConnection conn = new SqlConnection(DbConnectionString) )
{
SqlCommand cmd = new SqlCommand(queryString, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
Check your connection string code must not be a string its class which is getting connection string from web.config, so it should be like this
string DbConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["RBConnectionString"].ConnectionString;
You did not execute your SQlCommand, so will it insert the data, do this
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
its not the cause but the best practice to not to make your code vulnerable to SQLINjection, try this article
How To: Protect From SQL Injection in ASP.NET