无需关注字段类型,只要传入字段名与值的集合,自动生成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. http 超文本传输协议

    超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议.所有的WWW文件都必须遵守这个标准.设计HTTP最初的目的是为了提供一种发布和接 ...

  2. LR监控Windows资源

    1.监控准备: 监控方: 1)安装tcp/ip协议下的netbios 2)用administrator登录 被监控方: 1)被监控的Windows开启两个服务: Remote ProcedureCal ...

  3. 原生Android动作

    ACTION_ALL_APPS:打开一个列出所有已安装应用程序的Activity.通常,此操作又启动器处理. ACTION_ANSWER:打开一个处理来电的Activity,通常这个动作是由本地电话拨 ...

  4. Linux Apache 怎么修改工作模式

    Apache默认为prefork模式,主要是考虑到稳定性的原因. 要切换到worker模式,则需要登录到linux上,进行如下操作: 进入/usr/sbin目录 cd /usr/sbin 将当前的pr ...

  5. POJ 3083

    ---恢复内容开始--- http://poj.org/problem?id=3083 题目大意就是给你要你从S走到E,且只有.代表的地方才是可以走的,有三种方式的走法. 一.是向左优先转,从S到E的 ...

  6. MySQL 全文搜索支持, mysql 5.6.4支持Innodb的全文检索和类memcache的nosql支持

    背景:搞个个人博客的全文搜索得用like啥的,现在mysql版本号已经大于5.6.4了也就支持了innodb的全文搜索了,刚查了下目前版本号都到MySQL Community Server 5.6.1 ...

  7. ARGB32 to YUV12 利用 SDL1.2 SDL_ttf 在视频表面输出文本

    提示:ARGB alpha通道的A + 原YUV表面的y0 + 要写进去的y1 = 计算出新的y2. 计算公式为 ( y1 * a + y0 * ( 255 - a ) ) / 255 void rg ...

  8. Java数据类型中String、Integer、int相互间的转换

    1.Integer转换成int的方法 Integer i;  int k = i.intValue(); 即Integer.intValue(); 2.int转换成Integer int i; Int ...

  9. [Android Pro] 监听Blutooth打开广播

    <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission a ...

  10. 解决Unable to reach a settlement: [diffie-hellman-group1-sha1, diffie-hellman-group-exchange-sha1] and [curve25519-sha256@li

    SharpSSH或JSCH使用diffie-hellman-group1-sha1和diffie-hellman-group-exchange-sha1密钥交换算法,而OpenSSH在6.7p1版本之 ...