无需关注字段类型,只要传入字段名与值的集合,自动生成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. javax.inject中@Inject、@Named、@Qualifier和@Provider用法

    @Inject @Inject支持构造函数.方法和字段注解,也可能使用于静态实例成员.可注解成员可以是任意修饰符(private,package-private,protected,public).注 ...

  2. Gradle用户指南(3)-构建Java项目

    1.构建基本的Java项目 为了使用 Java 插件,添加下面代码到构建文件: build.gradle apply plugin: 'java' 这个就是 定义一个 Java 项目的全部.它会将 J ...

  3. ASP.Net 5 上传文件通过虚拟路径存储

    先贴上代码 [HttpPost] public IActionResult ImportTeaching(IFormFile file) { string root = @"Temp/tea ...

  4. C开发基础--函数调用栈

    发现有一些问题几乎是所有的新人都会遇到,而且也常因为缺乏一些基本的知识而无从下手.函数调用栈的内容就是其中之一.于是花点时间把以前写的内容整理出来. 程序在运行期间,内存中有一块区域,用来实现程序的函 ...

  5. subverison的安装与注意事项

    1.安装 :官网下载 http://blog.csdn.net/sinboy/article/details/4000524 http://sourceforge.net/projects/win32 ...

  6. Bookshelf 2

    Bookshelf 2 Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Submit  ...

  7. 22.整数二进制表示中1的个数[Get1BitCount]

    [题目] 输入一个整数,求该整数的二进制表达中有多少个1.例如输入10,由于其二进制表示为1010,有两个1,因此输出2. [分析] 如果一个整数不为0,那么这个整数至少有一位是1.如果我们把这个整数 ...

  8. Android Studio项目引入外部库注意事项(PullToRefresh)

    Android Studio开发App项目时引入第三方库是个比较麻烦的事情.之前导入Volley就折腾了好久,导入下拉刷新控件PullToRefresh时又碰到了各种问题.在此记录一下,以便查阅. 一 ...

  9. iOS NSURLConnection和异步网络请求

    在日常应用中,我们往往使用AFNetworking等第三方库来实现网络请求部分.这篇文章会简要地介绍一下如何使用NSURLConnection来进行异步的网络请求. 我们先看一个小demo - (vo ...

  10. 12.python笔记之mysqldb模块

    一.使用python调用模块操作MYsql 2.x版本使用mysqldb模块 3.x版本使用pymysql模块 1.数据库常用操作: 使用Navicat for MySql软件来操作 show dat ...