c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)(二) 作者:PeterXu  来源:Blog.优快云  Blog: http://blog.csdn.net/peterreg/版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。本文地址:http://blog.csdn.net/peterreg/archive/2008/04/02/2243123.aspx使用静态工厂模式,通过传入枚举 阅读详情

首先定义数据库操作的标准接口IDBAccess,定义接口的基本功能;

通过基本的接口设置,完成数据访问的统一抽象。

public interface IDBAccess
    
...{
        
void Init(string strServer, string strDataBase, string strUser, string strPwd);
        
void Open();
        
void Close();
        
bool TestConn();
        
int RunNoQuery(string strCmd);
        DataTable RunQuery(
string strCmd);
        DBType DBType 
...{ get;}
        
int GetFiledMax(string strTable, string strField);
        DataTable Tables 
...{ get; }
        DataTable GetColumns();
        DataTable GetColumns(
string strTable);
    }

使用静态工厂模式,通过传入枚举型参数 ,动态创建访问实例

实现模式上采用基本实现接口,派生类继承基类的虚函数,从而实现代码的耦合较低,有很好的扩展性。

public enum DBType
    
...{
        Access,
        SQL,
        DB2,
        Oracle,
        MySQL
    }


 
public static class DBAccessFactory
    
...{
        
public static IDBAccess Create(DBType type)
        
...{
            IDBAccess IRet 
= null;
            
switch (type)
            
...{
                
case DBType.Access:
                    IRet 
= new Access(type);
                    
break;

                
case DBType.SQL:
                    IRet 
= new SQL(type);
                    
break;

                
default:
                    
break;
            }

            
return IRet;
        }


        
private abstract class DBAccess : IDBAccess
        
...{
            
protected DbConnection m_oConn = null;
            
protected const string CON_strServer = "Server";
            
protected const string CON_strDataBase = "Data Source";
            
protected const string CON_strUser = "UID";
            
protected const string CON_strPwd = "PWD";
            
protected const string CON_strConnTimeOut = "Connect Timeout = 2";
            
private DBType m_eDBType = DBType.Access;

            
protected DBAccess(DBType type)
            
...{
                
this.m_eDBType = type;
            }


            
public DBType DBType
            
...{
                
get ...{ return this.m_eDBType; }
            }


            
public void Init(string strServer, string strDataBase, string strUser, string strPwd)
            
...{
                
this.InitConn(strServer, strDataBase, strUser, strPwd);
            }


            
public void Open()
            
...{
                
if (this.m_oConn != null)
                
...{
                    
this.m_oConn.Open();
                }

            }


            
public int RunNoQuery(string strCmd)
            
...{
                
int iRet = 0;
                
try
                
...{
                    DbCommand oCmd 
= this.GetCmd(strCmd);
                    
if (oCmd != null)
                    
...{
                        iRet 
= oCmd.ExecuteNonQuery();
                    }

                }

                
catch (Exception ex)
                
...{
                    
throw (new Exception(ex.Message));
                }

                
return iRet;
            }


            
public int GetFiledMax(string strTable, string strField)
            
...{
                
int iRet = -1;
                DataTable dt 
= this.RunQuery("Select Max(" + strField + ") From " + strTable);
                
if (dt != null && dt.Rows.Count == 1)
                
...{
                    iRet 
= dt.Rows[0][0] is DBNull ? 0 : Convert.ToInt32(dt.Rows[0][0]);
                }

                
return iRet;
            }


            
public DataTable RunQuery(string strCmd)
            
...{
                DataTable dt 
= new DataTable();
                DbDataAdapter adp 
= this.DbAdp;
                adp.SelectCommand 
= this.GetCmd(strCmd);
                adp.Fill(dt);
                
return dt;
            }


            
public void Close()
            
...{
                
if (this.m_oConn != null && this.m_oConn.State == System.Data.ConnectionState.Open)
                
...{
                    
this.m_oConn.Close();
                }

            }


            
public bool TestConn()
            
...{
                
bool bRet = true;
                
try
                
...{
                    
if (this.m_oConn.State != System.Data.ConnectionState.Open)
                    
...{
                        
this.m_oConn.Open();
                    }

                    bRet 
= this.m_oConn.State == System.Data.ConnectionState.Open;
                }

                
catch
                
...{
                    bRet 
= false;
                }

                
this.Close();
                
return bRet;
            }


            
public abstract DataTable Tables ...{ get; }
            
public abstract DataTable GetColumns();
            
public abstract DataTable GetColumns(string strTable);

            
protected abstract void InitConn(string strServer, string strDataBase, string strUser, string strPwd);
            
protected abstract DbCommand GetCmd(string strCmd);
            
protected abstract DbDataAdapter DbAdp ...{ get;}
        }

   }

各派生类的具体实现,此时只要实现DBAccess的各个虚函数即可。

private class Access : DBAccess
        
...{
            
public Access(DBType type)
                : 
base(type)
            
...{
            }


            
protected override void InitConn(string strServer, string strDataBase, string strUser, string strPwd)
            
...{
                
string strConn = "Provider = ";
                
switch (strDataBase.Substring(strDataBase.LastIndexOf('.') + 1).ToLower())
                
...{
                    
case "mdb":     // 2000, 2003
                        strConn += "Microsoft.Jet.OleDb.4.0;";
                        
break;

                    
case "accdb":   // 2007
                        strConn += "Microsoft.ACE.OLEDB.12.0;";
                        
break;

                    
default:
                        
throw (new Exception("Unknown Access Version."));
                    
//break;
                }

                strConn 
+= CON_strDataBase + " = " + strDataBase;
                
//strConn += CON_strUser + " = " + strUser;
                
//strConn += CON_strPwd + " = " + strPwd;
                base.m_oConn = new OleDbConnection(strConn);
            }


            
protected override DbCommand GetCmd(string strCmd)
            
...{
                
return new OleDbCommand(strCmd, (OleDbConnection)base.m_oConn);
            }


            
protected override DbDataAdapter DbAdp
            
...{
                
get ...{ return new OleDbDataAdapter(); }
            }


            
public override DataTable Tables
            
...{
                
get
                
...{
                    
return ((OleDbConnection)base.m_oConn).GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] ...{ null, null, null, "Table" });
                }

            }


            
public override DataTable GetColumns()
            
...{
                DataTable dt 
= new DataTable();
                
foreach (DataRow row in this.Tables.Rows)
                
...{
                    dt.Merge(
this.GetColumns(row["TABLE_NAME"].ToString()));
                }

                
return dt;
            }


            
public override DataTable GetColumns(string strTable)
            
...{
                
return ((OleDbConnection)base.m_oConn).GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] ...{ null, null, strTable, null });
            }

        }


        
private class SQL : DBAccess
        
...{
            
public SQL(DBType type)
                : 
base(type)
            
...{
            }


            
protected override void InitConn(string strServer, string strDataBase, string strUser, string strPwd)
            
...{
                
string strConn = CON_strServer + " = " + strServer + ";";
                strConn 
+= CON_strDataBase + " = " + strDataBase + ";";
                strConn 
+= CON_strUser + " = " + strUser + ";";
                strConn 
+= CON_strPwd + " = " + strPwd + ";";
                strConn 
+= CON_strConnTimeOut;
                
base.m_oConn = new SqlConnection(strConn);
            }


            
protected override DbCommand GetCmd(string strCmd)
            
...{
                
return new SqlCommand(strCmd, (SqlConnection)base.m_oConn);
            }


            
protected override DbDataAdapter DbAdp
            
...{
                
get ...{ return new SqlDataAdapter(); }
            }


            
public override DataTable Tables
            
...{
                
get ...{ return ((SqlConnection)base.m_oConn).GetSchema("Tables", null); }
            }


            
public override DataTable GetColumns()
            
...{
                
return ((SqlConnection)base.m_oConn).GetSchema("Columns", null);
            }


            
public override DataTable GetColumns(string strTable)
            
...{
                
return ((SqlConnection)base.m_oConn).GetSchema("Columns", new string[] ...{ null, null, strTable, null });
            }

        }

 

整个例子的完整代码如下,VS2008下编译测试通过,本人已通过它实现N个项目,欢迎大家评测,谢谢指教

public enum DBType
    
...{
        Access,
        SQL,
        DB2,
        Oracle,
        MySQL
    }


    
public interface IDBAccess
    
...{
        
void Init(string strServer, string strDataBase, string strUser, string strPwd);
        
void Open();
        
void Close();
        
bool TestConn();
        
int RunNoQuery(string strCmd);
        DataTable RunQuery(
string strCmd);
        DBType DBType 
...{ get;}
        
int GetFiledMax(string strTable, string strField);
        DataTable Tables 
...{ get; }
        DataTable GetColumns();
        DataTable GetColumns(
string strTable);
    }


    
public static class DBAccessFactory
    
...{
        
public static IDBAccess Create(DBType type)
        
...{
            IDBAccess IRet 
= null;
            
switch (type)
            
...{
                
case DBType.Access:
                    IRet 
= new Access(type);
                    
break;

                
case DBType.SQL:
                    IRet 
= new SQL(type);
                    
break;

                
default:
                    
break;
            }

            
return IRet;
        }


        
private abstract class DBAccess : IDBAccess
        
...{
            
protected DbConnection m_oConn = null;
            
protected const string CON_strServer = "Server";
            
protected const string CON_strDataBase = "Data Source";
            
protected const string CON_strUser = "UID";
            
protected const string CON_strPwd = "PWD";
            
protected const string CON_strConnTimeOut = "Connect Timeout = 2";
            
private DBType m_eDBType = DBType.Access;

            
protected DBAccess(DBType type)
            
...{
                
this.m_eDBType = type;
            }


            
public DBType DBType
            
...{
                
get ...{ return this.m_eDBType; }
            }


            
public void Init(string strServer, string strDataBase, string strUser, string strPwd)
            
...{
                
this.InitConn(strServer, strDataBase, strUser, strPwd);
            }


            
public void Open()
            
...{
                
if (this.m_oConn != null)
                
...{
                    
this.m_oConn.Open();
                }

            }


            
public int RunNoQuery(string strCmd)
            
...{
                
int iRet = 0;
                
try
                
...{
                    DbCommand oCmd 
= this.GetCmd(strCmd);
                    
if (oCmd != null)
                    
...{
                        iRet 
= oCmd.ExecuteNonQuery();
                    }

                }

                
catch (Exception ex)
                
...{
                    
throw (new Exception(ex.Message));
                }

                
return iRet;
            }


            
public int GetFiledMax(string strTable, string strField)
            
...{
                
int iRet = -1;
                DataTable dt 
= this.RunQuery("Select Max(" + strField + ") From " + strTable);
                
if (dt != null && dt.Rows.Count == 1)
                
...{
                    iRet 
= dt.Rows[0][0] is DBNull ? 0 : Convert.ToInt32(dt.Rows[0][0]);
                }

                
return iRet;
            }


            
public DataTable RunQuery(string strCmd)
            
...{
                DataTable dt 
= new DataTable();
                DbDataAdapter adp 
= this.DbAdp;
                adp.SelectCommand 
= this.GetCmd(strCmd);
                adp.Fill(dt);
                
return dt;
            }


            
public void Close()
            
...{
                
if (this.m_oConn != null && this.m_oConn.State == System.Data.ConnectionState.Open)
                
...{
                    
this.m_oConn.Close();
                }

            }


            
public bool TestConn()
            
...{
                
bool bRet = true;
                
try
                
...{
                    
if (this.m_oConn.State != System.Data.ConnectionState.Open)
                    
...{
                        
this.m_oConn.Open();
                    }

                    bRet 
= this.m_oConn.State == System.Data.ConnectionState.Open;
                }

                
catch
                
...{
                    bRet 
= false;
                }

                
this.Close();
                
return bRet;
            }


            
public abstract DataTable Tables ...{ get; }
            
public abstract DataTable GetColumns();
            
public abstract DataTable GetColumns(string strTable);

            
protected abstract void InitConn(string strServer, string strDataBase, string strUser, string strPwd);
            
protected abstract DbCommand GetCmd(string strCmd);
            
protected abstract DbDataAdapter DbAdp ...{ get;}
        }


        
Access, SQL#region Access, SQL

        
private class Access : DBAccess
        
...{
            
public Access(DBType type)
                : 
base(type)
            
...{
            }


            
protected override void InitConn(string strServer, string strDataBase, string strUser, string strPwd)
            
...{
                
string strConn = "Provider = ";
                
switch (strDataBase.Substring(strDataBase.LastIndexOf('.') + 1).ToLower())
                
...{
                    
case "mdb":     // 2000, 2003
                        strConn += "Microsoft.Jet.OleDb.4.0;";
                        
break;

                    
case "accdb":   // 2007
                        strConn += "Microsoft.ACE.OLEDB.12.0;";
                        
break;

                    
default:
                        
throw (new Exception("Unknown Access Version."));
                    
//break;
                }

                strConn 
+= CON_strDataBase + " = " + strDataBase;
                
//strConn += CON_strUser + " = " + strUser;
                
//strConn += CON_strPwd + " = " + strPwd;
                base.m_oConn = new OleDbConnection(strConn);
            }


            
protected override DbCommand GetCmd(string strCmd)
            
...{
                
return new OleDbCommand(strCmd, (OleDbConnection)base.m_oConn);
            }


            
protected override DbDataAdapter DbAdp
            
...{
                
get ...{ return new OleDbDataAdapter(); }
            }


            
public override DataTable Tables
            
...{
                
get
                
...{
                    
return ((OleDbConnection)base.m_oConn).GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] ...{ null, null, null, "Table" });
                }

            }


            
public override DataTable GetColumns()
            
...{
                DataTable dt 
= new DataTable();
                
foreach (DataRow row in this.Tables.Rows)
                
...{
                    dt.Merge(
this.GetColumns(row["TABLE_NAME"].ToString()));
                }

                
return dt;
            }


            
public override DataTable GetColumns(string strTable)
            
...{
                
return ((OleDbConnection)base.m_oConn).GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] ...{ null, null, strTable, null });
            }

        }


        
private class SQL : DBAccess
        
...{
            
public SQL(DBType type)
                : 
base(type)
            
...{
            }


            
protected override void InitConn(string strServer, string strDataBase, string strUser, string strPwd)
            
...{
                
string strConn = CON_strServer + " = " + strServer + ";";
                strConn 
+= CON_strDataBase + " = " + strDataBase + ";";
                strConn 
+= CON_strUser + " = " + strUser + ";";
                strConn 
+= CON_strPwd + " = " + strPwd + ";";
                strConn 
+= CON_strConnTimeOut;
                
base.m_oConn = new SqlConnection(strConn);
            }


            
protected override DbCommand GetCmd(string strCmd)
            
...{
                
return new SqlCommand(strCmd, (SqlConnection)base.m_oConn);
            }


            
protected override DbDataAdapter DbAdp
            
...{
                
get ...{ return new SqlDataAdapter(); }
            }


            
public override DataTable Tables
            
...{
                
get ...{ return ((SqlConnection)base.m_oConn).GetSchema("Tables", null); }
            }


            
public override DataTable GetColumns()
            
...{
                
return ((SqlConnection)base.m_oConn).GetSchema("Columns", null);
            }


            
public override DataTable GetColumns(string strTable)
            
...{
                
return ((SqlConnection)base.m_oConn).GetSchema("Columns", new string[] ...{ null, null, strTable, null });
            }

        }


        
#endregion

    }

C#--SQL server数据库基本操作(连接、增、删、改、查)封装 写在前面: SQLserver的C#封装:https://www.cnblogs.com/mexihq/p/11636785.html Oracle的C#封装:https://www.cnblogs.com/mexihq/p/11700741.html MySQL的C#封装:https://www.cnblogs.com/mexihq/p/12463423.html Access... 阅读详情

相关推荐

C#数据库操作封装类

自己用C#写好的一个专门操作几种常用数据库(sql server,access,oracle)的类。支持事务操作,参数传递,存储过程。dataset 的批量更新操作。

C#ado.net数据库操作(有封装现成代码和解释)

Connection、Command、DataAdapter、DataSet、DataReader

weixin_45756851的博客 1863

DRAM刷新refresh相关知识归类-基础小知识(三)

RAM每一位数据都是通过芯片内的一个小电容充电(或低电平)存储的。但随着时间的推移,电容逐渐失去电荷。为避免丢失存储的数据,必须定期刷新以将电荷(如果存在)恢复到其原始级别。此刷新过程包括读取每个位的值,然后将其写回。在此“刷新”期间,内存被占用,无法执行加载或存储位等正常操作。知道了应该这么做,但怎么去做以及有什么办法更有效率去做,就是接下来要整理的内容。

Paul 安的博客 1万+

C#数据库操作类的封装

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Data; namespace 尝试封装类 {     cla

gxiaozhe的专栏 634

华为、Cisco、H3C、中兴网络设备如何配置syslog日志采集

华为、Cisco、H3C、中兴网络设备如何配置syslog日志采集

weixin_40239644的博客 8705

RK3588零拷贝视频流水线实战:用GStreamer+Mpp实现8K硬解与DRM显示

本文深入探讨了在RK3588平台上构建零拷贝视频流水线的工程实践。通过结合GStreamer与MPP,实现了从8K视频硬解到DRM显示的全流程硬件加速,有效解决了高分辨率视频处理中的DDR带宽瓶颈问题。文章详细解析了dma-buf数据流机制、管道构建与性能优化策略,为多路视频并发处理提供了高效的系统架构解决方案。

github5actions的博客 1169

C#.NET万能数据库访问封装类(ACCESS、SQLServer、Oracle)

在app.config文件中写上数据库中连接信息: <appSettings> <add key="connectionstring" value="Data Source=LocalHost;Initial Catalog=Test001;User ID=sa;Password=aaaaaa" /> <add key="DataType" valu...

数据库 237

关于token无痛刷新的两个方案

目录方案一方案二 方案一 思路: 后端需要返回一个token过期的时间,在请求发起前拦截每个请求,判断token的有效时间是否已经过期,如果已过期,则暂时将请求挂起,先刷新token后再继续请求。 前期思考: 返回过期时间是为了判断是否过期的,但是如果服务器时间和系统时间不一致呢? 如果同时发起多个请求时怎么办? 实现: 因为是在请求前进行拦截,所以这里用axios的axios.interceptors.request.use()方法 首先,关于服务器时间和系统时间不一致的问题,我的解决方法是:

Yugoup的博客 2716

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)(四)

作者:PeterXu  来源:Blog.优快云  Blog: http://blog.csdn.net/peterreg/版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。本文地址:http://blog.csdn.net/peterreg/archive/2008/04/02/2243126.aspx整个例子的完整代码如下,VS2

PeterXu的专栏 2356

基于虚拟阻抗重塑的构网型VSG变流器SISO序阻抗建模与宽频振荡抑制策略分析(面向高比例新能源并网场景)

本文深入探讨了基于虚拟阻抗控制的构网型VSG变流器SISO序阻抗建模技术及其在高比例新能源并网场景中的宽频振荡抑制策略。通过虚拟阻抗重塑,有效改善了变流器的阻抗特性,解决了次/超同步频段的振荡问题,并提供了参数设计、阻抗扫频验证等实用技巧,为新能源并网系统的稳定性提供了可靠解决方案。

weixin_29268385的博客 251

Index-TTS-1.5:多模态语音合成的技术演进与商业落地实践

本文深入探讨了Index-TTS-1.5在多模态语音合成领域的技术演进与商业落地。该模型基于GPT风格的自回归Transformer架构,通过优化条件编码器和引入字符-拼音混合建模,显著提升了语音生成的稳定性、精准度和真实感,实现了高质量的零样本语音克隆。文章还详细介绍了其云端体验、本地WebUI部署及ComfyUI集成等实战路径,并分析了其在虚拟数字人、个性化内容创作等商业场景中的应用潜力与挑战。

weixin_29098367的博客 402

【经典】c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)【转】http://hi.baidu.com/hou5757219/blog/item/ce34f51956998d73dab4bd95.html public enum DBType    ...{        Access,        SQL,        DB2,    

gxj022的专栏 741

ABAP 大规模数据并行处理实战,六套 Parallel Processing Framework 如何选,性能调优真正该盯住什么

如果今天真的面对那份执行 14 个小时的生产报表,我不会马上把原来的 Loop 改成 50 个aRFC。我会先用 SAT、ST12、SQL Monitor 和 HANA 侧工具确认时间到底花在哪里。如果 90% 时间其实消耗在一条低效 SQL 上,Parallel Processing 只是让 50 个 Worker 同时执行那条低效 SQL,数据库会比原来更痛苦。应该先把串行逻辑本身优化到合理水平。该做 Set-based Processing 的地方先交给 HANA。该避免SELECT。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 149

MSSQL,ORACLE,DB2,MYSQL,Access各类数据库使用GUID作为主键

不同的数据库生成GUID的方式不同,当然可以统一用程序来写,比如最后的c++生成guid的方式,但是有时候用数据库自带的方法,可以更简便。 什么是GUID? GUID: 即Globally Unique Identifier(全球唯一标识符) ,GUID是一个通过特定算法产生的二进制长度为128位的数字标识符,用于指示产品的唯一性。GUID 主要用于在拥有多个节点、多台计算机的

u012718690的专栏 2305

全志V3S嵌入式驱动开发(解决kernel 5.2.y wifi驱动问题)

​【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】 wifi模块,之前测试的时候,开发板上用的是esp8089,当时内核时4.14.y,测试也是通过的。链接地址在这里, https://blog.csdn.net/feixiaoxing/article/details/131178420?spm=1001.2014.3001.5501 那个时候测试的时候,我们就说过,wifi驱动可能是除了镜像制作之外,最复杂的一个

嵌入式-老费,一个分享专业嵌入式知识的blog 1158

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)2

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)2【转】http://hi.baidu.com/yuyang0105/blog/item/95f0b84798d6233686947339.html 使用静态工厂模式,通过传入枚举型参数 ,动态创建访问实例实现模式上采用基本实现接口,派生类继承基类的虚函数,从而实现代码的耦合较低,

gxj022的专栏 684

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)(三)

各派生类的具体实现,此时只要实现DBAccess的各个虚函数即可。        private class Access : DBAccess        ...{            public Access(DBType type)                : base(type)            ...{            }            prote

jiangxinyu的专栏 2020

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)(一)

作者:PeterXu  来源:Blog.优快云  Blog: http://blog.csdn.net/peterreg/版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章原始出版、作者信息和本声明。否则将追究法律责任。本文地址:http://blog.csdn.net/peterreg/archive/2008/04/02/2242981.aspx 首先定义数据库操作的标准接口

PeterXu的专栏 2100

(转)c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL)

c#下各种数据库操作的封装!(支持ACCESS,SQLSERVER,DB2,ORACLE,MYSQL) 首先定义数据库操作的标准接口IDBAccess,定义接口的基本功能; 通过基本的接口设置,完成数据访问的统一抽象。 publicinterfaceIDBAccess...{voidInit(stringstrServer,stringstrDataBa...

weixin_30274627的博客 187
上一篇: C#.NET万能数据库访问封装类(ACCESS、SQLServer、Oracle)
下一篇: 关于SQL语句的自动生成
cuoban
博客等级 码龄24年 239粉丝 13原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值