根据C#实体类自动生成SQLServer数据库建表sql语句
程序员文章站
2022-06-15 13:48:18
...
不会偷懒的程序员不是好程序猿,没有什么技术点,就是对字符串进行解析,大神勿喷.虽然简单,但是很实用,可以节省不少时间.
注意项:
1.复制的时候按照样本复制;
2.拓展类型的话对着switch新增就行了;
3.可能有未知bug,建表的时候仔细再看看生成的sql语句.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace ClassAutoSetSQL
{
class Program
{
static void Main(string[] args)
{
string str = @"public class CarInvoice
{
public string success { get; set; }
public string fpdm { get; set; }
public string fplx { get; set; }
public string fphm { get; set; }
public DateTime kprq { get; set; }
public string xfMc { get; set; }
public string xfNsrsbh { get; set; }
public string xfContact { get; set; }
public string xfBank { get; set; }
public string gfMc { get; set; }
public string gfNsrsbh { get; set; }
public string gfContact { get; set; }
public string gfBank { get; set; }
public string code { get; set; }
public string num { get; set; }
public string del { get; set; }
public decimal taxamount { get; set; }
public decimal goodsamount { get; set; }
public decimal sumamount { get; set; }
public decimal quantityAmount { get; set; }
public string updateTime { get; set; }
public string remark { get; set; }
public CarGoodsData CarDoodData { get; set; }
}
";
str = Regex.Replace(str, @"[\r\n]", "");
string sqlhead = "";
string sqlbody = "";
for (int i = 0; i < str.Length; i++)
if (str[i] == 'p' && str[i + 1] == 'u' && str[i + 2] == 'b' && str[i + 3] == 'l' && str[i + 4] == 'i' && str[i + 5] == 'c')
{
if (i == 0)
{
i += 13;
for (; ; )
{
if (str[i] == '{') break;
sqlhead += str[i];
i++;
}
}
else {
string type = "";
string sqltype = "";
string sqlname = "";
i += 7;
for (; ; )
{
if (str[i] == ' ') break;
type += str[i];
i++;
}
switch (type)
{
case "string":
sqltype = " nvarchar(50),\r\n";
break;
case "bool":
sqltype = " nvarchar(50),\r\n";
break;
case "DateTime":
sqltype = " datetime,\r\n";
break;
case "decimal":
sqltype = " decimal(18, 0),\r\n";
break;
case "int":
sqltype = " int,\r\n";
break;
default :
sqltype = " "+type + ",\r\n";
break;
}
i++;
for (; ; )
{
if (str[i] == ' ') break;
sqlname += str[i];
i++;
}
sqlbody += sqlname + sqltype;
i += 13;
}
}
string sql = "create table " + sqlhead + "(\r" + sqlbody + ")";
Console.WriteLine(sql);
}
}
}