Im making a few static classes to avoid rewriting the same code multiple times and to keep all the database related methods in the same place.
the class look like this:
public static class Database_dbSurvey
{
public static DataSet GetQuestionari()
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default_connection"].ConnectionString);
string query = "[admin].[SRV_Categorie_Lista]";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.CommandType = CommandType.StoredProcedure;
//GetDataSet use the SqlDataAdapter.fill() method
return Utils.GetDataSet(cmd);
}
etc.... (others similar methods)
}
I want to reduce the code and I want to make it more "object oriented", so I started by making a property for the SqlConnection (which is the same for every methods of this class).
private static SqlConnection connection
{
get { return new SqlConnection(ConfigurationManager.ConnectionStrings["default_connection"].ConnectionString); }
}
The problem is that it works perfectly with SqlDataAdapter.fill(), till I use a method like this:
using (connection)
{
connection.Open();
cmd.ExecuteNonQuery();
}
Now, the next usage of the connection will throw the "not istanziated" exception and I can't understand why.
what is the correct way to define the connection property?
p.s.
if you have other suggestion on improving the code it will be higly appreciated
EDIT:
I still dont get it why the "new" keyword do not create another istance of the SQLConnection everytime I call it.
however I made some changes to make the code safer:
private static string connection_string
{
get { return ConfigurationManager.ConnectionStrings["Connection_dbPrysmianSurvey"].ConnectionString; }
}
public static DataSet GetQuestionari(string username)
{
string query = "[dbo].[SRV_Test_Lista]";
using (SqlConnection connection = new SqlConnection(connection_string))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", username);
return Utils.GetDataSet(cmd);
}
}
public static int CreaTest(string ID_questionario, string username)
{
string query = "[dbo].[srv_test_genera]";
using (SqlConnection connection = new SqlConnection(connection_string))
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID_categoria", ID_questionario);
cmd.Parameters.AddWithValue("#ID_utente", username);
connection.Open();
return (int)cmd.ExecuteScalar();
}
}
But considering the fact that I have 40-50 methods it's still is a pain to rewrite the same lines 40-50 times, any suggestions?
Do not use using keyword in your case.
It will dispose the connection after that using's scope is complete by calling SqlConnection.Dispose method.
using(connection) {...}'s equivalent -
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
connection.Dispose();
}
As #Parag Meshram mentioned, using keyword disposes everything inside itself when completed.
There are two ways I can suggest:
(1) Don't make connection a static method
private SqlConnection connection() { get { return new
SqlConnection(ConfigurationManager.ConnectionStrings["default_connection"].ConnectionString);}
}
then use it like
SqlConnection newConnection = connection();
using (newConnection) { ... }
Or
(2) Keep your static method as is but use it like this:
try {
connection.Open();
cmd.ExecuteNonQuery(); } catch {
throw; }
This way, your connection is not disposed.
I had the same problem a year ago and that's now I resolved it, using method (2).
Related
I have the following INSERT method in a C# web project. If I run the project without MySQL connection poling everything works fine, but when I activate Pooling=True in the DB connection string this method stops working, the insert statements never complete.
I realized how to modify the code to make it work, but I would like to understand what is happening and I hope you could help.
When I comment line //myR.Close(); everything works fine.
using MySql.Data.MySqlClient;
//query example consulta="INSERT INTO users (id, name) VALUES (1, 'Rob');
public static MySqlConnection GetWriteConnection()
{
string connStr = MySqlConnectionStrings.WriteConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static MySqlConnection GetReadConnection()
{
string connStr = MySqlConnectionStrings.ReadConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static bool Insert(string consulta)
{
MySqlConnection conn = BdaHelper.GetWriteConnection();
conn.Open();
using (conn)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand micomando = new MySqlCommand(consulta, conn);
micomando.ExecuteNonQuery(); //still not working
return true;
}
catch (Exception ex)
{
return false;
}
}
}
My app has also multi-thread concurrency and two types of database connections, one specifically for only-read purposes and other different for write. When an insert statement fails I don't get any error simply the change doesn't commit in the database. Reading the article in the comments I don't think this applies to this issue but I would add an example of my main program:
MySqlConnection readConnection = BdaHelper.GetReadConnection();
using (readConnection)
{
var users = GetUsers(readConnection);
var credentials = GetCredentials(readConnection);
//Example is the query that fails don't giving any exception
Insert("INSERT INTO login_log (id_user, date) VALUES (1, now())");
}
May the problem be caused because there are two concurrent connections?
I shouldn't reuse read connection, even is a different connection than the write connection?
Having a bit of an issue getting my insert to work properly. When I run the insert all within the same method, it works flawlessly... however when I try to send the Insert statement to my new Connection class (which I will have handle all database requests), I am getting the following error.
Note: I am using C# and Microsoft SQL Server.
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#CollectionGroupID".
I believe I am not sending the parameters over, however I am not sure of the best way to do this.
Here's my AddGame method:
public static void AddGame(int gameId)
{
string statement = "INSERT INTO Collection (CollectionGroupID, SharedID, UserID, GameID, Owned, Favorited, WishList, DeletedIndicator, AddUser, AddDate, ModUser, ModDate) VALUES (#CollectionGroupID, #SharedID, #UserID, #GameID, #Owned, #Favorited, #WishList, #DeletedIndicator, #AddUser, #AddDate, #ModUser, #ModDate)";
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.AddWithValue("#CollectionGroupID", "0");
cmd.Parameters.AddWithValue("#SharedID", "0");
cmd.Parameters.AddWithValue("#UserID", "0");
cmd.Parameters.AddWithValue("#GameID", gameId);
cmd.Parameters.AddWithValue("#Owned", "Y");
cmd.Parameters.AddWithValue("#Favorited", "N");
cmd.Parameters.AddWithValue("#WishList", "N");
cmd.Parameters.AddWithValue("#DeletedIndicator", "N");
cmd.Parameters.AddWithValue("#AddUser", "test/admin");
cmd.Parameters.AddWithValue("#AddDate", DateTime.Now);
cmd.Parameters.AddWithValue("#ModUser", "test/admin");
cmd.Parameters.AddWithValue("#ModDate", DateTime.Now);
Connection.Open();
Connection.Statement(statement);
Connection.Close();
}
}
And here is my Statement method in my Connection class
public static void Statement(string sql)
{
Console.WriteLine("Attempting to submit data to the database...");
try
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
Console.WriteLine(e);
}
}
I feel like perhaps I am overlooking a simple solution. Any help appreciated!
-Travis W.
Command parameter is defined in SqlCommand in your AddGame method
you are passing the raw Sql over to the Statement method and inside the method you are creating another SqlCommand without parameter defined. This is why the parameters are not being passed in.
you should just do
using (SqlConnection connection = new SqlConnection(connectionString))
{
//OR using (SqlConnection connection = Connection.Open())
//If you want to keep your Connection class to avoid having to pass in connection string.
using (SqlCommand cmd = new SqlCommand(statement, connection))
{
...
cmd.ExecuteNonQuery ()
}
}
inside your AddGame method
I'm a big fan of keeping my code simple and trim so it can be re-usable, on thing i'm struggling with is using the data reader for different types of objects, I had it in a method and found there were problems with connections closed or being left open. SO I am being forced, for the mean time to copy and paste the code, which is something I hate!!!
Is there any way I can scale this down so I can put it in a method and make it re-usable and nice?
ENT_AuctionBid ret = new ENT_AuctionBid();
try
{
SqlParameter[] Params = new SqlParameter[]{
new SqlParameter("#ID", ID )
};
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
using (SqlCommand command = new SqlCommand("GetItem", conn))
{
SqlDataReader reader;
command.CommandType = CommandType.StoredProcedure;
conn.Open();
command.Parameters.AddRange(Params);
reader = command.ExecuteReader(CommandBehavior.SingleRow);
while (reader.HasRows)
{
while (reader.Read())
{
//
ret = this.Convert(reader);
}
reader.NextResult();
}
reader.Close();
}
}
}
catch (Exception ex)
{
}
return ret;
You should use SQLDataAdapter.
Here's a nice example on how to use it:
http://www.dotnetperls.com/sqldataadapter
Also, you might want to consider switching to Entity Framework, it will make your data access much, much easier, but might be complicated in an existing project.
You can make it using a lot less lines:
// Skipped creating temp variable
try {
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
using (SqlCommand command = new SqlCommand("GetItem", conn) { CommandType = CommandType.StoredProcedure} ) {
command.Parameters.AddWithValue(#ID, ID);
conn.Open();
// reader is IDisposable, you can use using
using (var reader = command.ExecuteReader(CommandBehavior.SingleRow)) {
// Skipped parsing multiple result sets, you return after the first
// otherwise there's no point using SingleRow
// If nothing is read, return default value
return reader.Read() ? this.Convert(reader) : new ENT_AuctionBid();
}
}
}
catch (Exception ex) {
// Handle your exception here
}
// Return default value for error
return new ENT_AuctionBid();
All connections are closed using this code (because using is used). No unneeded loops are created, becuase you only expect a single row. And the temporary variable is not needed, so the abondend object is not created, only when it is used it is created.
This is a bit smaller:-
try
{
using (SqlConnection conn = new SqlConnection(this.ConnectionString))
{
using (SqlCommand command = new SqlCommand("GetItem", conn))
{
command.Paramaters.AddWithValue("#ID",ID);
command.CommandType = CommandType.StoredProcedure;
conn.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
//
ret = this.Convert(reader);
}
}
}
}
catch (Exception ex)
{
}
Create helper methods for creating and returning an object of type SqlCommand. Pass a connection object to this helper method as well as stored procedure name and parameters list (if any). If you have different objects that are created from the data reader, pass the data reader to a constructor and let it generate an object based on that data.
As for closing the connection you should always have try...catch...finally. In the finally section close the connection.
In my projects i usually solve this problem creating an utility class that contains all the methods to access to the DB and manage inside all the stuff related to the db connection and the adapter.
For example a class called DBSql which contains a connection (SqlConnection connection;) as private member and the following methods:
//execute the query passed to the function
public System.Data.DataSet ExecuteQuery(string query)
//returns if a query returns rows or not
public bool HasRows(string query)
//execute commands like update/insert/etc...
public int ExcuteNonQuery(string sql)
In my class, you just pass a string and the class initialize the various DataAdapter and Command to execute it and return a dataset. Obiously you can complicate it to manage parameters/transaction and everything else.
In this way you are sure that the connection and the object are always handled the same way, and, hopefully, in a correct way.
You can use a utility file, such as SqlHelper.cs from Microsoft Data Access Application Block. Then all the code you need is this:
using (SqlDataReader sdr = SqlHelper.ExecuteReader(this.ConnectionString, "GetItem", ID))
{
while (sdr.Read())
{
ret = this .Convert(sdr);
}
}
You could start using LINQ-to-SQL, which has it's own DataClass system in which you just drag-&-drop your database tables and stored procedures. Then you just have to create an instance at the top of your classes -- private MyCustomDataClass _db = new MyCustomDataClass(); and then you can just type in _db.<Here all datatables and SPROCs will appaer for you to choose>.
Example (from when all SPROCs are added to the DataClass)
private MyCustomDataClass _db = new MyCustomDataClass();
public void MethodToRunSPROC(string email, Guid userId)
{
_db.MySPORC_AddEmailToUser(email, userId);
}
I tried to insert some data into my database (sql server/local file) but it doesn't work.
public bool SaveCookie(string cookie, string expires)
{
SimpleDBM db = new SimpleDBM();
db.Connect();
try
{
string query = string.Format("INSERT INTO Cookies(cookie_value, cookie_expires) VALUES('{0}', '{1}');", cookie, expires);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
//...
SqlDataReader data = db.Query(ref cmd);
return data.Read();
}
catch
{
return false;
}
finally
{
db.Close();
}
}
The SimpleDBM class:
public class SimpleDBM {
public static string dbpath = #"...";
public static string dbname = "db.mdf";
public static string dfullPath = Path.Combine(dbpath, dbname);
public static string connStr = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;Connect Timeout=30;User Instance=True", dfullPath);
private SqlConnection con;
public void Connect()
{
con = new SqlConnection();
con.ConnectionString = connStr;
con.Open();
}
public SqlDataReader Query(ref SqlCommand cmd)
{
cmd.Connection = con;
return cmd.ExecuteReader();
}
public void Close()
{
con.Close();
}
}
Can someone point out my mistake? For other queries it seems to work fine.
Thanks in advance.
The problem seems to be that you're trying to execute a query that doesn't return a result set using the ExecuteReader method of the SqlCommand class which will attempt to execute your query and create and return a DataReader for an eventual result set.
You should use ExecuteNonQuery for INSERT and UPDATE sql statements.
SIDE NOTE
Not that it's the reason you're getting the error but you should also consider using SqlParamters instead of composing the values into the INSERT statement. Using prepared SQL statements generally gives a performance enhancement and also helps prevent SQL injection attacks.
For an example of using prepared statements, see the MSDN page or the Prepare method.
You are using a ExecuteReader when you should be using ExecuteNonQuery.
Not related to your error you really should not be using String.Format with SqlCommand. What you should do is
string query = "INSERT INTO Cookies(cookie_value, cookie_expires) VALUES(#cookie, #expires);", cookie, expires);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#cookie", cookie);
cmd.Parameters.AddWithValue("#expires", expires);
cmd.CommandText = query;
With your method ask your self if someone passed a cookie of ' ''); Drop table Cookies --? This is called a "Sql Injection Attack" and is one of the top 5 reasons websites get hacked.
EDIT
Just to help give another example of why using String.Format to pass values you did not generate is bad.
In an attempt to close my question on connections remaining open and exceeding the maximum pool, I'm trying tor rewrite the function that is used to connect to our database.
The function exists within a homegrown compiled library. using reflector I can see the code looks like this:
public SqlProvider([Optional, DefaultParameterValue("")] string StrConnection)
{
string str;
if (StrConnection == "")
{
str = ConfigurationSettings.AppSettings["ConStr"];
}
else
{
str = StrConnection;
}
SqlConnection connection = new SqlConnection(str);
connection.Open();
this.MyCommand = new SqlCommand();
SqlCommand myCommand = this.MyCommand;
myCommand.Connection = connection;
myCommand.CommandType = CommandType.Text;
myCommand = null;
this.MyDataAdapter = new SqlDataAdapter(this.MyCommand);
this.MyCommandBuilder = new SqlCommandBuilder(this.MyDataAdapter);
this.MyDataSet = new DataSet();
}
I'm planning on amending this to read
public SqlProvider([Optional, DefaultParameterValue("")] string StrConnection)
{
string str;
if (StrConnection == "")
{
str = ConfigurationSettings.AppSettings["ConStr"];
}
else
{
str = StrConnection;
}
using (SqlConnection connection = new SqlConnection(str))
{
connection.Open();
this.MyCommand = new SqlCommand();
SqlCommand myCommand = this.MyCommand;
myCommand.Connection = connection;
myCommand.CommandType = CommandType.Text;
myCommand = null;
this.MyDataAdapter = new SqlDataAdapter(this.MyCommand);
this.MyCommandBuilder = new SqlCommandBuilder(this.MyDataAdapter);
this.MyDataSet = new DataSet();
}
}
and then recompiling the dll.
Given that an instance of SQLProvider() is typically created at the top of a public class, and then that instance is used within class members (eg:
public class Banner
{
DSLibrary.DataProviders.SqlProvider db = new DSLibrary.DataProviders.SqlProvider(Defaults.ConnStr);
public Banner()
{
}
public DataTable GetBannerImages(string bannerLocation,int DeptId)
{
using (DSLibrary.DataProviders.SqlProvider db = new DSLibrary.DataProviders.SqlProvider(Defaults.ConnStr))
{
DataTable dt = new DataTable();
//Add Parameter #BannerLocation for Banner of Specific Location
//Call proc_getBannerImages Stored procedure for Banner Images
db.AddStoredProcParameter("#BannerLocation", SqlDbType.VarChar, ParameterDirection.Input, 100, bannerLocation);
db.AddStoredProcParameter("#DeptId", SqlDbType.Int, ParameterDirection.Input, 0, DeptId);
dt = db.ExecuteStoredProcedure("proc_getBannerImages");
return dt;
}
}
}
am I going about this the right way? It seems to me the connection will be disposed of before the data has actually been retrieved. Also, Visual Studio tells me that SQLProvider() must be implicitly convertible to System.IDisposable - how would I go about implementing this?
I tried wrapping all the members of class Banner in a using (DSLibrary.DataProviders.SqlProvider db = new DSLibrary.DataProviders.SqlProvider(Defaults.ConnStr)){} statement but intellisense then displays a "Invalid token 'using' in class, struct, or interface member declaration" error.
What is the best way to go about this?
UPDATE
I've tried disassembling adjusting and recompiling the DSLibrary, but as CHris_Lively says, I thinkit's doing nothing for me. Changing the instance in question to what I preceive to be a more standard format works so far:
public DataTable GetBannerImages(string bannerLocation,int DeptId)
{
using (SqlConnection conn = new SqlConnection(Defaults.ConnStr))
{
SqlCommand cmd = new SqlCommand("proc_getBannerImages", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#BannerLocation", bannerLocation));
cmd.Parameters.Add(new SqlParameter("#DeptId", DeptId));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
I'm about to look into the Enterprise library, seems like it might be the way forward.
It is not recommended to hold on to connections any longer than required (See also Chapter 14 of Improving .NET Application Performance and Scalability: Patterns and Practices from Microsoft Press).
In practice I'd change your class to instead not have the SqlConnection (or SqlDataAdapter or SqlCommandBuilder) as a member on the class (if you must, then you should implement the IDisposable pattern), but instead create new instances, wrapped in using statements on the class methods that need to use them.
I DO NOT think you are doing it correctly. As soon as you hit the end of the using block, the SqlConnection variable will become unusable . If you want to use it outside the constructor, dont put the using {} around the SqlConnection variable (The sqlcommand variable MyCommand is using it indirectly outside the constructor).
Instead, make you SqlProvider class implement IDisposable, and call Dispose on the MyCommand, MyDataAdapter, MyDataSet etc. variables there.
You probably should have something like this in your SqlProvider class :
public void Dispose()
{
if (MyCommand != null)
{
MyCommand.Dispose();
}
//... Similarly for MyDataAdapter,MyDataSet etc.
}
Your class needs to implement the IDisposable interface if you want to use it in a using block. See http://msdn.microsoft.com/en-us/library/system.idisposable.dispose%28v=VS.100%29.aspx for guidelines on dispose() and IDisposable.
You're close. However, a couple issues.
First, it looks like that whole DSLibrary isn't buying you anything at all.
When doing data access you typically want to structure it where acquiring the connection and executing the command are in the same function. You're methods should only return the result of the operation. This way you can cleanly use the IDisposable interface of the connection, command, and reader.
The following example uses Enterprise Library. Note that the Db doesn't have a using clause. It doesn't implement IDisposable. Instead, the command is responsible for letting go of the connection when it goes out of scope:
public static DataTable GetBannerImages(String bannerLocation, Int32 departmentId)
{
DataTable result = new DataTable();
result.Locale = CultureInfo.CurrentCulture;
Database db = DatabaseFactory.CreateDatabase("NamedConnectionStringFromConfig");
using (DbCommand dbCommand = db.GetStoredProcCommand("proc_getBannerImages"))
{
db.AddInParameter(dbCommand, "BannerLocation", DbType.String, bannerLocation);
db.AddInParameter(dbCommand, "DeptId", DbType.Int32, departmentId);
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
SopDataAdapter dta = new SopDataAdapter(); // descended from DbDataAdapter
dta.FillFromReader(result, reader);
} // using dataReader
} // using dbCommand
return result;
} // method::GetBannerImages
You probably already have something that will convert a reader to a datatable, if not just look into subclassing the System.Data.Common.DbDataAdapter class
I've had tremendous success with the Enterprise Library. It's fast, efficient, and when going this route I've never had memory leaks or db connection issues.
There is no need to set variables to null - anyway they will be deleted by GC.
Also you need to call Dispose() or Close() for all classes that implements IDisposable. e.g. SqlConnection.
You can do that manually:
SqlConnection conn = null;
try
{
// use conn
}
finally
{
if (conn != null)
conn.Close();
}
or automatically using using block:
using (SqlConnection = new SqlConnection())
{
// use conn
}
(as you do)
Also you can decrease your code a bit using operator ?:
string str = String.IsNullOrEmpty(StrConnection) ? ConfigurationSettings.AppSettings["ConStr"] : StrConnection;
or ??:
string str = StrConnection ?? ConfigurationSettings.AppSettings["ConStr"];