نوشته شده توسط
jas1387
پس باید کانکشنم را توی یه کلاس مجزا به صورت عمومی تعریف کنم تا بهتونم توی هر کدوم از کلاس های مربوط به جدول هام ازش استفاده کنم ، درسته ؟
بهترین روش:
thread specific singleton
#if SQLite
public static SQLiteConnection Connection
{
get
{
initCon();
return Con[Thread.CurrentThread];
}
}
#endif
#if SqlServer
public static SqlConnection Connection
{
get
{
initCon();
return Con[Thread.CurrentThread];
}
}
#endif
#if SQLite
private static Dictionary<Thread, SQLiteConnection> Con;
#endif
#if SqlServer
private static Dictionary<Thread, SqlConnection> Con;
#endif
#if SqlServer
private static void initCon()
{
if (Con == null)
{
Con = new Dictionary<Thread, SqlConnection>();
}
SqlConnection connection = null;
if (!Con.ContainsKey(Thread.CurrentThread))
{
connection = Esfand.ProfileManagement.SQLServer.GetConnection() ;
connection.Open();
Con.Add(Thread.CurrentThread, connection);
ExecuteNonQuery("USE [Esfand]", connection);
}
else
{
connection = Con[Thread.CurrentThread];
}
while (connection.State != ConnectionState.Open)
{
}
}
#endif
internal static void RefreshConnections()
{
Collection<Thread> collection = new Collection<Thread>();
foreach (Thread thread in Con.Keys)
{
if ((thread == null) || (thread.ThreadState == System.Threading.ThreadState.Stopped))
{
collection.Add(thread);
}
}
foreach (Thread thread in collection)
{
Con.Remove(thread);
}
collection.Clear();
}
#if SQLite
public static SQLiteConnection Connection
{
get
{
initCon();
return Con[Thread.CurrentThread];
}
}
#endif
#if SqlServer
public static SqlConnection Connection
{
get
{
initCon();
return Con[Thread.CurrentThread];
}
}
#endif
#if SqlServer
internal static SqlDataReader ExecuteReader(string Text)
{
initCon();
SqlCommand command = new SqlCommand(Text, Connection);
return command.ExecuteReader();
}
#endif
#if SQLite
internal static SQLiteDataReader ExecuteReader(string Text, SQLiteConnection Connection)
{
SQLiteCommand command = new SQLiteCommand(Text, Connection);
return command.ExecuteReader();
}
#endif
#if SqlServer
internal static SqlDataReader ExecuteReader(string Text, SqlConnection Connection)
{
SqlCommand command = new SqlCommand(Text, Connection);
return command.ExecuteReader();
}
#endif