首页 > 数据库 >【C#】JSON转DataTable存入数据库

【C#】JSON转DataTable存入数据库

时间:2023-06-08 16:01:02浏览次数:43  
标签:case string C# break column JSON cSharpType typeof DataTable

由于JSON直接转DataTable可能会存在类型丢失
如下:
在这里插入图片描述

采用读取数据库表字段类型构建DataTable

/// <summary>
 /// JSON转DataTale存入数据库
 /// </summary>
 /// <param name="json"></param>
 public static void JsonDataTableTest(string json)
 {
     string sql = string.Format("SELECT name AS column_name , TYPE_NAME(system_type_id) AS column_type  FROM sys.columns WHERE object_id = OBJECT_ID(N'{0}')", "JSON_TO_DATATABLE_TEST");
     var dt = DbHelperSQL.Query(sql).Tables[0];
     DataTable mrow = new DataTable();
     foreach (DataRow row in dt.Rows)
     {
         string column_name = Convert.ToString(row["column_name"]);
         string column_type = Convert.ToString(row["column_type"]);
         Console.WriteLine($"column_name:{column_name},column_type:{column_type}");
         // 从数据库获取类型,构造DataTable,JSON直接转DataTable可能会类型丢失
         mrow.Columns.Add(column_name, DBTypeToCSharpType(column_type));
     }
     
     JArray data = JObject.Parse(json)["data"] as JArray;
     foreach(JObject o in data)
     {
         var row = mrow.NewRow();
         foreach (JProperty property in o.Properties())
         {
             if (mrow.Columns.Contains(property.Name))
             {
                 // 如果JSON的值为null
                 if(o[property.Name].Type == JTokenType.Null)
                 {
                     row[property.Name] = DBNull.Value;
                 }
                 else
                 {
                     row[property.Name] = o[property.Name];
                 }
                 
             }
         }
         mrow.Rows.Add(row);
     }

     Console.WriteLine(mrow);

     AddTable(mrow, "JSON_TO_DATATABLE_TEST");
 }

 /// <summary>
 /// 将数据库数据类型字符串,转为C#数据类型字符串。
 /// </summary>
 /// <param name="dbType">数据库数据类型字符串。</param>
 /// <returns>C#数据类型</returns>
 private static Type DBTypeToCSharpType(string dbType)
 {
     Type cSharpType = null;
     switch (dbType.ToLower())
     {
         case "bit":
             cSharpType = typeof(bool);
             break;
         case "tinyint":
             cSharpType = typeof(byte);
             break;
         case "smallint":
             cSharpType = typeof(short);
             break;
         case "int":
             cSharpType = typeof(int);
             break;
         case "bigint":
             cSharpType = typeof(long);
             break;
         case "real":
             cSharpType = typeof(float);
             break;
         case "float":
             cSharpType = typeof(double);
             break;
         case "smallmoney":
         case "money":
         case "decimal":
         case "numeric":
             cSharpType = typeof(decimal);
             break;
         case "char":
         case "varchar":
         case "nchar":
         case "nvarchar":
         case "text":
         case "ntext":
             cSharpType = typeof(string);
             break;
         case "samlltime":
         case "date":
         case "smalldatetime":
         case "datetime":
         case "datetime2":
         case "datetimeoffset":
             cSharpType = typeof(DateTime);
             break;
         case "timestamp":
         case "image":
         case "binary":
         case "varbinary":
             cSharpType = typeof(byte[]);
             break;
         case "uniqueidentifier":
             cSharpType = typeof(Guid);
             break;
         case "variant":
         case "sql_variant":
             cSharpType = typeof(object);
             break;
         default:
             cSharpType = typeof(string);
             break;
     }
     return cSharpType;
 }


 /// <summary>
 /// 批量更新
 /// </summary>
 /// <param name="dt">更新的内容</param>
 /// <param name="tableName">目标表</param>
 /// <returns></returns>
 public static Boolean AddTable(DataTable dt, string tableName)
 {
     using (SqlConnection sqlCon = new SqlConnection(DbHelperSQL.connectionString))
     {
         try
         {
             sqlCon.Open();
             using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlCon))
             {
                 bulkCopy.DestinationTableName = tableName;
                 for (int i = 0; i < dt.Columns.Count; i++)
                 {
                     bulkCopy.ColumnMappings.Add(dt.Columns[i].Caption.ToString(), dt.Columns[i].Caption.ToString());
                 }
                 bulkCopy.WriteToServer(dt);
                 return true;
             }
         }
         catch (Exception ex)
         {
             throw ex;
         }
         finally
         {
             sqlCon.Close();
         }
     }
 }

案例

private static void Main(string[] args)
{
   
    JsonDataTableTest(@"{""data"":[{""num"":100,""name"":""xiuyuan"",""time"":""2023-10-01 00:00:33""},{""num"":100.33,""name"":""xiaoming""}]}");
}

在这里插入图片描述

在这里插入图片描述

标签:case,string,C#,break,column,JSON,cSharpType,typeof,DataTable
From: https://www.cnblogs.com/xiuyuandashen/p/17466756.html

相关文章

  • 使用VS2022打包C#项目生成setup文件并部署
    首先安装工具新建Setup项目先将\bin\Debug下的生成文件添加到里面添加文件夹将我们需要的文件放入添加项目输出在用户桌面添加快捷方式简单的安装其实右键项目=》生成,然后就在debug这个目录下下一步下一步就可以了安装好桌面就有了添加卸载程序1.右......
  • CANoe _ DBC 的创建过程
    在Canoe中创建DBC(DatabaseContainer)文件,用于描述和定义CAN总线上的节点、消息和信号,遵循以下步骤:1.打开Canoe启动Canoe软件。2.创建新项目在Canoe的菜单栏中,选择"File"(文件)->"New"(新建)->"Project"(项目),或使用快捷键Ctrl+N。填写项目的名称和保存路径,然后点击"OK"(确定)。3.......
  • springmvc加文件上传支持
     找个sping.xml之类的,加入配置以及引用<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> <dependency><groupId>commons-fileupload</groupId>......
  • Nginx conf for fastapi backend project with variables
    带变量的nginx后端项目配置不同的api项目,挂载不同的域名,只需在配置夹里,修改文件名(建议文件名和域名保持一致)、修改端口号、修改第5行第22行backend_api后面的编号、修改第11行的项目名、可能还需要修改第12行的文件夹名、修改第14行的域名$cat/etc/nginx/sites-avaliable/myap......
  • Some demos of supervisor conf
    conffilesin/etc/supervisor/conf.d/VersionSupervisorisinstalledbyapt,andit'sversionis:sudosupervisord--version4.1.0ConffilesThereareDjangoprojects,FastAPIprojects,CelerybeatandworkerinthecloudserverDjangoProject......
  • .net core 因路径原因导致的JSON解析错误
    因解析json配置文件导致的错误:JsonReaderException:'0xEF'isaninvalidescapablecharacterwithinaJSONstring.Thestringshouldbecorrectlyescaped.LineNumber如何解决?{  "path":"D:\工作资料\技术资料"}改为{   "path":"D:......
  • CF1338 Div.1 做题记录
    ACF题面假定用到的最大的数是\(x\),那么一个数最大可以增大\(2^x-1\)。题目只要求不降,所以求出将\(a_i<a_{i-1}\)变成\(a_i=a_{i-1}\)时需要增大的最大值。求出这个数的二进制位数即可。点击查看代码#include<bits/stdc++.h>#defineullunsignedlonglong#definell......
  • Docker 部署 MariaDB
    下载镜像dockerpullmariadb:10.9.6启动容器dockerrun-d--namemariadb-p13306:3306-v'/data/mariadb/data:/var/lib/mysql'-e"MARIADB_ROOT_PASSWORD=123456"mariadb:10.9.6进行连接 ......
  • nodejs package.json
    package.json是用来识别项目并且处理项目的依赖关系的{"name":"名",//包名字"version":"1.0.0",//版本"description":"描述","main":"index.js",//入口文件"scripts":{//指定运行脚本......
  • Atomic-命令与控制战术
    Atomic-命令与控制战术可以编入使用落实到安全策略且有效的战术编号参考:https://atomicredteam.io/atomics/#command-and-control具体战术概览command-and-controlT1573EncryptedChannel加密通道T1572ProtocolTunneling协议隧道T1571Non-StandardPort......