基于三层架构下的公共数据访问方法(Sqlite数据库)

作者总结了一下,使用Winform的三层架构做窗体应用程序,在数据访问方面,有用到纯sql语句方法、参数方法、存储过程方法。

那么什么是三层架构呢?

UI---存放Form窗体---(用户所关心的)

业务逻辑层----存放业务传递(BLL)

数据访问层----底层的数据处理方法(DAL)

数据公共访问方法---SqlHelper(DBUtilty)

使用三层架构设计Winform程序,能够达到”高内聚、低耦合“.团队分工明确,适用于大型的企业级项目

 

现在我提供一下SQLite数据库的访问方法

第一步:配置数据库。在App.config里

<connectionStrings>
<add name="sqlite" connectionString="data source=|datadirectory|..\..\Hosptial.db;Pooling=true;FailIfMissing=false" providerName="System.Data.SQLite" />
</connectionStrings>

注意:我把数据库文件放在外层了,所以就必须多加【..\..\】,如果放在bin--debug文件加下就要写成|datadirectory|Hosptial.db

第二步:连接配置文件

1.新建一个类SqlHelper.引入命名空间:using System.Data; using System.Data.Sqlite; using System.Configuration;

2.添加引用:引用--添加引用--勾选System.Configuration

3.连接配置文件:在类中添加代码: private static string conn = ConfigurationManager.ConnectionStrings["sqlite"].ToString();

注意:中括号里的["___"]名称必须要与App.Config里的connectionStrings的name相同,否则会出现异常

4.建立公共方法(错误输出到本地的方法,参照我的另一篇博客https://www.cnblogs.com/970728-qi/p/9826476.html)

  •  普通数据访问方法
 
  
//1.执行sql语句,并返回受影响的行数,在使用Command向数据库发送增、删、改命令时,通常使用ExecuteNonQuery方法
public static int Update(string sql)
{
SQLiteConnection sqlcon = new SQLiteConnection(conn);
SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
try
{
sqlcon.Open();
return sqlcmd.ExecuteNonQuery();
}
catch (Exception e)
{
PrintError(e.Message);//将错误信息保存到本地
throw new Exception("调用 public static int Update(string sql)方法时出错" + e.Message);
}
finally
{
sqlcon.Close();//关闭练连接
}
}
  //2.执行Sql语句,返回结果集的第一行,第一列。通常使用ExecuteScalar方法
        public static object SingResult(string sql)
        {
            SQLiteConnection sqlcon = new SQLiteConnection(conn);
            SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
            try
            {
                sqlcon.Open();
                return sqlcmd.ExecuteScalar();
            }
            catch (Exception e)
            {
                PrintError(e.Message);
                throw new Exception("调用public static object SingResult(string  sql)方法时出错:" + e.Message);
            }
            finally
            {
                sqlcon.Close();
            }
        }
 
  
        //3.执行sql语句,生成一个包含数据的SQLiteDataReader对象实例
        public static SQLiteDataReader GetReader(string sql)
        {
            SQLiteConnection sqlcon = new SQLiteConnection(conn);
            SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
            try
            {
                sqlcon.Open();
                return sqlcmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception e)
            {
                sqlcon.Close();
                PrintError(e.Message);
                throw new Exception("调用public static SQLiteDataReader GetReader(string sql)方法时出错:" + e.Message);
            }
        }
 
  
//4.产生dataTable对象     
 public static DataTable GetDataTable(string sql)
        {
            SQLiteConnection sqlcon = new SQLiteConnection(conn);
            SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
            SQLiteDataAdapter da = new SQLiteDataAdapter(sqlcmd);//创建适配器对象
            DataTable table = new DataTable();
            try
            {
                sqlcon.Open(); 
                da.Fill(table);
                return table;
            }
            catch (Exception e)
            {

                PrintError(e.Message);
                throw new Exception("调用public static DataSet GetDataSet(string sql)方法时出错:" + e.Message);
            }
            finally
            {
                sqlcon.Close();
            }
        }
  •  参数方法
      public static int UpdateParam(string sql, SQLiteParameter[] parameter)
            {
                SQLiteConnection sqlcon = new SQLiteConnection(conn);
                SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
                try
                {
                    sqlcon.Open();
                    sqlcmd.Parameters.AddRange(parameter);
                    return sqlcmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    PrintError(e.Message);
                    throw new Exception("调用 public static int UpdateParam(string sql, SQLiteParameter[] parameter)方法时出错" + e.Message);
                }
                finally
                {
                    sqlcon.Close();
                }
            }
    
            public static object SingleResultParam(string sql, SQLiteParameter[] parameter)
            {
                SQLiteConnection sqlcon = new SQLiteConnection(conn);
                SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
                try
                {
                    sqlcon.Open();
                    sqlcmd.Parameters.AddRange(parameter);
                    return sqlcmd.ExecuteScalar();
                }
                catch (Exception e)
                {
                    PrintError(e.Message);
    
                    throw new Exception("调用 public static object SingleResultParam(string sql, SQLiteParameter[] parameter)方法时出错" + e.Message);
                }
                finally
                {
                    sqlcon.Close();
                }
            }
    
            public static SQLiteDataReader GetReaderParam(string sql, SQLiteParameter[] parameter)
            {
                SQLiteConnection sqlcon = new SQLiteConnection(conn);
                SQLiteCommand sqlcmd = new SQLiteCommand(sql, sqlcon);
                try
                {
                    sqlcon.Open();
                    sqlcmd.Parameters.AddRange(parameter);
                    return sqlcmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch (Exception e)
                {
                    sqlcon.Close();
                    PrintError(e.Message);
                    throw new Exception("调用public  static SQLiteDataReaderParam GetReader(string sql,SQLiteParameter[] parameter)方法时出错" + e.Message);
                }
            }
  • 存储过程方法
          public static int UpdateProce(string spName, SQLiteParameter[] parameter)
            {
                SQLiteConnection sqlcon = new SQLiteConnection(conn);
                SQLiteCommand sqlcmd = new SQLiteCommand(spName, sqlcon);
                try
                {
                    sqlcon.Open();
                    sqlcmd.CommandType = CommandType.StoredProcedure;
                    sqlcmd.Parameters.AddRange(parameter);
                    return sqlcmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    PrintError(e.Message);
                    throw new Exception("调用public static int UpdateProce(string spName,SQLiteParameter[] parameter)方法出错:" + e.Message);
                }
                finally
                {
                    sqlcon.Close();
                }
    
            }
            public static object SingleResultProc(string spName, SQLiteParameter[] paramter)
            {
                SQLiteConnection sqlcon = new SQLiteConnection(conn);
                SQLiteCommand sqlcmd = new SQLiteCommand(spName, sqlcon);
                try
                {
                    sqlcon.Open();
                    sqlcmd.CommandType = CommandType.StoredProcedure;
                    sqlcmd.Parameters.AddRange(paramter);
                    return sqlcmd.ExecuteScalar();
    
                }
                catch (Exception e)
                {
                    PrintError(e.Message);
                    throw new Exception("调用  public static object  SingleResultProc(string spName,SQLiteParameter[] paramter)方法出错:" + e.Message);
                }
                finally
                {
                    sqlcon.Close();
                }
            }
            public static SQLiteDataReader GetReaderProc(string spName, SQLiteParameter[] parameter)
            {
                SQLiteConnection sqlcon = new SQLiteConnection(conn);
                SQLiteCommand sqlcmd = new SQLiteCommand(spName, sqlcon);
                try
                {
                    sqlcon.Open();
                    sqlcmd.Parameters.AddRange(parameter);
                    sqlcmd.CommandType = CommandType.StoredProcedure;
                    return sqlcmd.ExecuteReader(CommandBehavior.CloseConnection);
    
                }
                catch (Exception e)
                {
                    sqlcon.Close();
                    PrintError(e.Message);
                    throw new Exception("调用   public static SQLiteDataReader GetReaderProc(string spName, SQLiteParameter[] parameter)方法出错:" + e.Message);
                }
    
            }

    因为会写第一个基本的sqlite语句方法,其他两种都大致相同。作者就不再赘述了,如有错误欢迎指正,如若转载,请标注出处。

转载于:https://www.cnblogs.com/970728-qi/p/10091935.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
数据库三层架构通常包括表示层、业务逻辑层和数据访问层。在Python中,可以使用各种框架和库来实现这些层次结构。以下是一个简单的示例代码,演示如何使用Python和SQLite实现数据库三层架构: 表示层(Presentation Layer):该层与用户界面交互,接收和处理用户的请求,并将结果返回给用户。 ```python # 导入必要的库和模块 from business_logic_layer import BusinessLogicLayer # 创建业务逻辑层对象 bll = BusinessLogicLayer() # 处理用户输入 while True: user_input = input("请输入要执行的操作:") if user_input == "exit": break result = bll.process_input(user_input) print(result) ``` 业务逻辑层(Business Logic Layer):该层包含应用程序的业务逻辑和规则,处理表示层传递的请求,并将结果传递给数据访问层。 ```python # 导入必要的库和模块 from data_access_layer import DataAccessLayer # 创建数据访问层对象 dal = DataAccessLayer() class BusinessLogicLayer: def process_input(self, user_input): # 处理用户输入并调用相应的数据访问方法 if user_input.startswith("添加"): args = user_input.split(" ")[1:] return dal.insert_data(args[0], args[1]) elif user_input.startswith("查询"): args = user_input.split(" ")[1:] return dal.query_data(args[0]) else: return "无效命令!" ``` 数据访问层(Data Access Layer):该层与数据库交互,执行数据操作(例如插入、查询、更新和删除)。 ```python # 导入必要的库和模块 import sqlite3 class DataAccessLayer: def __init__(self): # 连接数据库 self.conn = sqlite3.connect("mydatabase.db") self.cursor = self.conn.cursor() def insert_data(self, name, age): # 插入数据 self.cursor.execute("INSERT INTO mytable (name, age) VALUES (?, ?)", (name, age)) self.conn.commit() return "插入成功!" def query_data(self, name): # 查询数据 self.cursor.execute("SELECT * FROM mytable WHERE name = ?", (name,)) result = self.cursor.fetchone() if result is None: return "未找到数据!" else: return f"姓名:{result[0]},年龄:{result[1]}" ``` 请注意,这只是一个简单的示例,实际上,要实现更复杂的应用程序,还需要考虑安全性、性能和可扩展性等因素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值