时间:2021-07-01 10:21:17 帮助过:12人阅读
将数据库操作封装成一个工具类
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();//关闭数据库
}
}
使用工具类
TraditionalSQLServerDBManager manager = new TraditionalSQLServerDBManager();
manager.ExcuteSQL(@"INSERT INTO [test2].[dbo].[BitTable] ([IsDelete]) VALUES(1)");
封装工具类
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;
}
}
调用方法
List<BitModel> list = new BLL.AboutDBManager().GetBitModel();
连接其他数据库,引用目标数据库相关DLL,将SqlConnection改为目标Connection即可。
如:
using System.Data.SQLite;
private SQLiteConnection connection;
多个不同的数据库连接,比如MySQL,SQL Server,Oracle等,可以考虑采用接口实现多态
数据库操作 连接 增删改查 断开
标签:instance ase 语句 关闭 value 不同的 new t 连接 data