Traditional way
Encapsulating database Operations as a tool class
using System.Data;using System.Data.SqlClient;public class TraditionalSQLServerDBManager{ SqlConnection con; public TraditionalSQLServerDBManager() { con = new SqlConnection(); con.ConnectionString = "Server=;DataBase=;Uid=;pwd=;"; con.Open(); } public void ExcuteSQL(string sql) { SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = sql; SqlDataReader dr = com.ExecuteReader();//执行SQL语句 dr.Close();//关闭执行 con.Close();//关闭数据库 }}
Using the tool class
TraditionalSQLServerDBManager manager = new TraditionalSQLServerDBManager();manager.ExcuteSQL(@"INSERT INTO [test2].[dbo].[BitTable] ([IsDelete]) VALUES(1)");
Using third-party libraries Dapper
Package Tool Class
public class DbManager<T> where T : class{ private static DbManager<T> instance; private static object _lock = new object(); private SqlConnection connection; public static DbManager<T> Instance { get { lock (_lock) { if (instance == null) { instance = new DbManager<T>(); } } return instance; } } public DbManager() { connection = new SqlConnection("Server=;DataBase=;Uid=;pwd=;"); connection.Open(); } public IEnumerable<T> QueryBySQL(string sql) { return connection.Query<T>(sql); } public bool ExecuteOne(string sql) { if (connection.Execute(sql) != 0) return true; return false; }}
Calling methods
List<BitModel> list = new BLL.AboutDBManager().GetBitModel();
Connect to other databases, reference the target database related DLLs, and change SqlConnection to target connection.
Such as:
using System.Data.SQLite;private SQLiteConnection connection;
Other
A number of different database connections, such as Mysql,sql Server,oracle, may consider using interfaces to achieve polymorphic
Database Operation connection Additions and deletions change check disconnect