无需关注字段类型,只要传入字段名与值的集合,自动生成Ms sql server SQL语句。
详见Test()方法

using System;

namespace Fan.iData.SqlUtility
{ public class SqlBuilder
{
private System.Data.DataView ct;
private string _tableName;
private string _ConnName; public SqlBuilder(string tableName)
{
_tableName = tableName;
_ConnName = ""; ct = GetColumnsType(); if (ct == null || ct.Table.Rows.Count == 0)
throw new Exception("要操作的表不存在!");
}
public SqlBuilder(string tableName,string connname)
{
//
_tableName=tableName;
if (connname==null)
_ConnName="";
else
_ConnName = connname; ct=GetColumnsType(); if (ct==null || ct.Table.Rows.Count==0)
throw new Exception("要操作的表不存在!");
} /// <summary>
/// 生成Insert语句
/// </summary>
/// <param name="tn"></param>
/// <param name="v"></param>
/// <param name="type">0=空值以null替代;1=空值转换(字符型为'',数值型为0,日期型为null);2=空值跳过(这时值取决于数据库的默认值设置)</param>
/// <returns></returns>
public string BuildInsertSql(System.Collections.Specialized.NameValueCollection v,int type)
{ if (ct==null || ct.Table.Rows.Count==0)
{
throw new Exception("要操作的表或字段不存在!");
}
//将V name全部改成小写
System.Collections.Specialized.NameValueCollection lowerv=new System.Collections.Specialized.NameValueCollection();
for ( int x=0;x<v.Count;x++)
{
string vn=v.GetKey(x).ToLower();
string vv="";
if (v[x] !=null)
vv=v[x].ToString();
lowerv.Add(vn,vv);
}
v=lowerv; int colcount=0; string columns="",values=""; string vKeys=Key2String(v).ToLower(); for (int i=0;i<ct.Table.Rows.Count;i++)
{
string coln=ct.Table.Rows[i]["name"].ToString(); if (v!=null && vKeys.IndexOf(","+coln.ToLower()+",")!=-1)
{
colcount++; string colv=v[coln.ToLower()].ToString();
int collen=int.Parse(ct.Table.Rows[i]["length"].ToString())
,coltype=int.Parse(ct.Table.Rows[i]["xtype"].ToString()); //coltype
//0=数据
//1=字符型
//2=日期型
//-1=不支持的类型 if (coltype==-1)
throw new Exception("出现不支持的数据类型!"); if (colv==null || colv=="")
{
#region 空值
if (type==0)
{
columns+=(columns.Equals(string.Empty))?" ["+ coln +"] ":", ["+ coln +"] ";
values+=(values.Equals(string.Empty))?" null ":", null ";
}
else if (type==1)
{
columns+=(columns.Equals(string.Empty))?" ["+ coln +"] ":", ["+ coln +"] "; if (coltype==0)
values+=(values.Equals(string.Empty))?" 0 ":", 0 ";
else if (coltype==1)
values+=(values.Equals(string.Empty))?" '' ":", '' ";
else if (coltype==2)
values += (values.Equals(string.Empty)) ? " N'' " : ", N'' ";
else
values+=(values.Equals(string.Empty))?" null ":", null ";
}
else
{
continue;
}
#endregion }
else
{
#region 代入字段值 //简单判断字符型的长度,可以自己加其它的判断
// if (coltype==1 && colv.Length>collen)
// {
// throw new Exception("要插入的字符串长度超过数据库设置!");
// } //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
if (coltype==0 || coltype==4)
{
columns+=(columns.Equals(string.Empty))?" ["+ coln +"] ":", ["+ coln +"] ";
values+=(values.Equals(string.Empty))?" "+ colv +" ":", "+ colv +" ";
}
else if (coltype==1 || coltype==3)
{
colv=colv.Replace("'","''");
columns+=(columns.Equals(string.Empty))?" ["+ coln +"] ":", ["+ coln +"] ";
values+=(values.Equals(string.Empty))?" '"+ colv +"' ":", '"+ colv +"' ";
}
else if (coltype == 2)
{
colv = colv.Replace("'", "''");
columns += (columns.Equals(string.Empty)) ? " [" + coln + "] " : ", [" + coln + "] ";
values += (values.Equals(string.Empty)) ? " N'" + colv + "' " : ", N'" + colv + "' ";
}
else
{
continue;
} #endregion
}
}
} if (v!=null && colcount!=v.Count)
throw new Exception("指定的字段列表中某些字段不存在!"); if (!columns.Equals(string.Empty) && !values.Equals(string.Empty))
{
string sql = "Insert into {0} ({1}) values ({2})";
return string.Format(sql,_tableName,columns,values);
}
else
return string.Empty; }
public string BuildInsertSql(System.Collections.Specialized.NameValueCollection v)
{
return BuildInsertSql(v,0);
}

  接下来还有段

        /// <summary>
/// 生成update语句
/// </summary>
/// <param name="tn"></param>
/// <param name="v"></param>
/// <param name="type">0=空值以null替代;1=空值转换(字符型为'',数值型为0,日期型为null);2=空值跳过</param>
/// <returns></returns>
public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v
,System.Collections.Specialized.NameValueCollection identity,int type)
{
if (ct==null || ct.Table.Rows.Count==)
{
throw new Exception("要操作的表或字段不存在!");
} //将V name全部改成小写
System.Collections.Specialized.NameValueCollection lowerv=new System.Collections.Specialized.NameValueCollection();
for ( int x=;x<v.Count;x++)
{
string vn=v.GetKey(x).ToLower();
string vv="";
if (v[x] !=null)
vv=v[x].ToString();
lowerv.Add(vn,vv);
}
v=lowerv; //将V name全部改成小写
System.Collections.Specialized.NameValueCollection lowerid=new System.Collections.Specialized.NameValueCollection();
for ( int x=;x<identity.Count;x++)
{
string vn=identity.GetKey(x).ToLower();
string vv="";
if (identity[x] !=null)
vv=identity[x].ToString();
lowerid.Add(vn,vv);
}
identity=lowerid; string setvalues="",identitycolumns="";
int idcount=
,colcount=; string vKeys=Key2String(v).ToLower()
,idKeys=Key2String(identity).ToLower(); #region 生成Set串
for (int i=;i<ct.Table.Rows.Count;i++)
{
string coln=ct.Table.Rows[i]["name"].ToString(); if (identity!=null && idKeys.IndexOf(","+coln.ToLower()+",")!=-)
{
idcount++; string colv=identity[coln.ToLower()].ToString();
int coltype=int.Parse(ct.Table.Rows[i]["xtype"].ToString()); if (colv==null)
throw new Exception("指定的条件没有给出匹配值!"); //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
if (coltype== || coltype==)
{
identitycolumns+=(identitycolumns.Equals(string.Empty))?" ["+ coln +"]="+ colv +" ":"and ["+ coln +"]="+ colv +" ";
}
else if (coltype== || coltype==)
{
colv=colv.Replace("'","''");
identitycolumns+=(identitycolumns.Equals(string.Empty))?" ["+ coln +"]='"+ colv +"' ":"and ["+ coln +"]='"+ colv +"' ";
}
else if (coltype == )
{
colv = colv.Replace("'", "''");
identitycolumns += (identitycolumns.Equals(string.Empty)) ? " [" + coln + "]=N'" + colv + "' " : "and [" + coln + "]=N'" + colv + "' ";
} //这里存在一个小缺陷,多个条件间只能是与操作 } if (v!=null && vKeys.IndexOf(","+coln.ToLower()+",")!=-)
{
colcount++;
string colv=v[coln.ToLower()].ToString();
int collen=int.Parse(ct.Table.Rows[i]["length"].ToString())
,coltype=int.Parse(ct.Table.Rows[i]["xtype"].ToString()); //coltype
//0=数据
//1=字符型
//2=日期型
//-1=不支持的类型 if (coltype==-)
throw new Exception("出现不支持的数据类型!"); if (colv==null || colv=="")
{
#region 空值
//0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
if (type==)
{
setvalues+=(setvalues.Equals(string.Empty))?" ["+ coln +"]=null ":", ["+ coln +"]=null ";
}
else if (type==)
{
if (coltype==)
setvalues+=(setvalues.Equals(string.Empty))?" ["+ coln +"]=0 ":", ["+ coln +"]=0 ";
else if (coltype==)
setvalues+=(setvalues.Equals(string.Empty))?" ["+ coln +"]='' ":", ["+ coln +"]='' ";
else if (coltype==)
setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=N'' " : ", [" + coln + "]=N'' ";
else
setvalues+=(setvalues.Equals(string.Empty))?" ["+ coln +"]=null ":", ["+ coln +"]=null ";
} #endregion }
else
{
#region 代入字段值 //简单判断字符型的长度,可以加其它的判断
// if (coltype==1 && colv.Length>collen)
// {
// throw new Exception("要插入的字符串长度超过数据库设置!");
// } //0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据
if (coltype== || coltype==)
{
setvalues+=(setvalues.Equals(string.Empty))?" ["+ coln +"]="+ colv +" ":", ["+ coln +"]="+ colv +" ";
}
else if (coltype== || coltype==)
{
colv=colv.Replace("'","''");
setvalues+=(setvalues.Equals(string.Empty))?" ["+ coln +"]='"+ colv +"' ":", ["+ coln +"]='"+ colv +"' ";
}
else if (coltype == )
{
colv = colv.Replace("'", "''");
setvalues += (setvalues.Equals(string.Empty)) ? " [" + coln + "]=N'" + colv + "' " : ", [" + coln + "]=N'" + colv + "' ";
} #endregion
}
}
}
#endregion if (identity!=null && idcount!=identity.Count)
throw new Exception("指定的更新条件中某些字段不存在!"); if (v!=null && colcount!=v.Count)
throw new Exception("指定的字段列表中某些字段不存在!"); if (!setvalues.Equals(string.Empty))
{
string sql="";
if (identity!=null && identity.Count>)
{
sql="update {0} set {1} where {2}";
sql=string.Format(sql,_tableName,setvalues,identitycolumns);
}
else
{
sql = "update {0} set {1}";
sql=string.Format(sql,_tableName,setvalues);
}
return sql;
}
else
return string.Empty;
}
public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v,System.Collections.Specialized.NameValueCollection identity)
{
return BuildUpdateSql(v,identity,);
}
public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v,string idcolumn,string idvalue,int type)
{
System.Collections.Specialized.NameValueCollection identity=new System.Collections.Specialized.NameValueCollection();
identity.Add(idcolumn,idvalue);
return BuildUpdateSql(v,identity,type);
}
public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v,string idcolumn,string idvalue)
{
return BuildUpdateSql(v,idcolumn,idvalue,);
} /// <summary>
/// 生成没有Where条件的Update语句
/// </summary>
/// <param name="v"></param>
/// <param name="type"></param>
/// <returns></returns>
public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v,int type)
{
return BuildUpdateSql(v,null,type);
} /// <summary>
/// 生成没有Where条件的Update语句
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public string BuildUpdateSql(System.Collections.Specialized.NameValueCollection v)
{
return BuildUpdateSql(v,null,);
} /// <summary>
///
/// </summary>
/// <returns></returns>
private System.Data.DataView GetColumnsType()
{ Fan.iData.DB idb; //数据库连接类,改成自己的数据库连接
if (_ConnName == "")
idb = new Fan.iData.DB();
else
idb = new Fan.iData.DB(_ConnName); string sql = @"
select a.[name],a.[length]
,case
when a.xusertype in (127,104,106,62,56,60,108,59,52,122,48) then 0
when a.xusertype in (175,35,167) then 1
when a.xusertype in (239,99,231) then 2
when a.xusertype in (61,58) then 3
when a.xusertype in (165,173,36) then 4
when a.xusertype in (34,98,241,189,256) then -1 else -1 end [xtype]
from syscolumns a
where object_id('" + _tableName + @"')=a.[id] order by a.colid
";
return idb.GetDataView(sql); #region
//0=数值型;1=字符型;2=Unicode字符型;3=日期型;4=二进制数据;-1=不支持的类型
//name xtype
//bigint 127
//binary 173
//bit 104
//char 175
//datetime 61
//decimal 106
//float 62
//image 34
//int 56
//money 60
//nchar 239
//ntext 99
//numeric 108
//nvarchar 231
//real 59
//smalldatetime 58
//smallint 52
//smallmoney 122
//sql_variant 98
//sysname 231
//text 35
//timestamp 189
//tinyint 48
//uniqueidentifier 36
//varbinary 165
//varchar 167
//xml 241
#endregion } private string Key2String(System.Collections.Specialized.NameValueCollection k)
{
string keystring=",";
for (int i=;k!=null && i<k.Count;i++)
{
keystring+=k.GetKey(i)+',';
}
return keystring;
} private void Test()
{
System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
nvc.Add("col1", "value1");
nvc.Add("col2", "value2");
SqlBuilder isql = new SqlBuilder("testTable"); string InsertSql=isql.BuildInsertSql(nvc);
string UpdateSql = isql.BuildUpdateSql(nvc, "idCol", "value"); }
}
}

两段连起来就行了。

,下面代码中数据库连接部分需要修改成你自己的数据连接代码。

一个自动生成插入与更新SQL语句的小类的更多相关文章

  1. EF-记录程序自动生成并执行的sql语句日志

    在EntityFramework的CodeFirst模式中,我们想将程序自动生成的sql语句和执行过程记录到日志中,方便以后查看和分析. 在EF的6.x版本中,在DbContext中有一个Databa ...

  2. (转载)根据数据字典表定义的表结构,生成创建表的SQL语句

    <来源网址:http://www.delphifans.com/infoview/Article_221.html>根据数据字典表定义的表结构,生成创建表的SQL语句 //1.  类名:T ...

  3. Mybatis——SQL语句构建器类

    SQL语句构建器类 问题 Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL语句.这么来做通常是由于SQL语句需要动态来生成-否则可以将它们放到外部文件或者存储过程中.正如你已经看到的 ...

  4. Java-MyBatis:MyBatis 3 | SQL 语句构建器类

    ylbtech-Java-MyBatis:MyBatis 3 | SQL 语句构建器类 1.返回顶部 1. SQL语句构建器类 问题 Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL ...

  5. ASP.NET MVC深入浅出(被替换) 第一节: 结合EF的本地缓存属性来介绍【EF增删改操作】的几种形式 第三节: EF调用普通SQL语句的两类封装(ExecuteSqlCommand和SqlQuery ) 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法 第六节: EF高级属性(二) 之延迟加载、立即加载、显示加载(含导航属性) 第十节: EF的三种追踪

    ASP.NET MVC深入浅出(被替换)   一. 谈情怀-ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态 ...

  6. php中soap的使用实例以及生成WSDL文件,提供自动生成WSDL文件的类库——SoapDiscovery.class.php类

    1. web service普及: Webservice soap wsdl区别之个人见解 Web Service实现业务诉求:  Web Service是真正“办事”的那个,提供一种办事接口的统称. ...

  7. Mybatis自动生成xml文件、dao接口、实体类

    Mybatis可以通过逆向工程,实现自动生成xml文件.dao接口.实体类 以下使用的是Intellij Idea进行自动生成 一.首先,要在pom.xml中导入插件,在<build>中加 ...

  8. @InsertProvider 根据bean属性,自动生成插入sql语句

    以Test为例,用mybatis的@InsertProvider的注解插入数据的时候,每次都要写类似于 Mapper类 @Mapper public interface TestDao { @Inse ...

  9. 厚溥教育1718部数据库连接作业答案,分装一个操作数据库而无需写SQL语句的函数

    <?php header("Content-type:text/html;charset=utf8"); //PHP操作数据库的函数 function phpsql($dbc ...

随机推荐

  1. H2Database数据类型

    数据类型   整数(INT) 布尔型(BOOLEAN) 微整数(TINYINT) 小整数(SMALLINT) 大整数(BIGINT) 标识符(IDENTITY) 货币数(DECIMAL) 双精度实数( ...

  2. Java并发编程笔记—基础知识—实用案例

    如何正确停止一个线程 1)共享变量的使用 中断线程最好的,最受推荐的方式是,使用共享变量(shared variable)发出信号,告诉线程必须停止正在运行的任务.线程必须周期性的核查这一变量(尤其在 ...

  3. CloudPlatform和CloudStack的关系

    The Scalr team is at the CloudStack Collab Conf, and this post summarizes a few things we learned. C ...

  4. cocos基础教程(3)cocos3.x版本目录结构介绍

    简介 cocos2d-x-3.x版本进行了很多优化,比如:将TTF字体用Atlas缓存,节点重排序官方声称提升了10倍速度,查找.移除节点方面也提高了10%,拆分渲染层到独立的线程运行: 另外,coc ...

  5. 通过Spring @PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

    关于在spring  容器初始化 bean 和销毁前所做的操作定义方式有三种: 第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作 第二 ...

  6. 获取IOS 设备基本信息

    原地址:http://www.cnblogs.com/U-tansuo/p/ios_basis_info.html 1.获取设备类型  (Iphone/ipad 几?) #import "s ...

  7. PHP学习之一晚撸下W3chscool

    PHP 多维数组 其实简单的而言,多维数组就是由单个的数组组成的,两个数组嵌套组成一个二维数组,三个顾名思义就是三维数组. 先来一个简单的数组. 数字是key,引号里的是value <?php ...

  8. bwa的使用方法

    bwa的使用需要两中输入文件:    Reference genome data(fasta格式 .fa, .fasta, .fna)    Short reads data (fastaq格式 .f ...

  9. BZOJ 1002 [ FJOI 2007 ]

    -------------------------萌萌哒分割线------------------------- 题目很容易看懂,数据范围也不大.当然可以卡过暴力的人了. 在n=1时很明显是一种,如下 ...

  10. c++ const总结

    [本文链接] http://www.cnblogs.com/hellogiser/p/cplusplus-const-summay.html 看到const 关键字,C++程序员首先想到的可能是con ...