using System ;
using System.Collections.Generic ;
using System.Data ;
using System.Globalization ;
using System.IO ;
using System.Linq ;
using System.Text ;
using System.Threading.Tasks ;
namespace GenerateClass.Util
{
public class DbUtil
{
public static string folderName = "GenFolder" ; // 文件夹名称
public static void openFile ( string tbname , string infoStr )
{
// 创建文件夹
string folderPath = Path . Combine ( Environment . CurrentDirectory , folderName ) ;
Directory . CreateDirectory ( folderPath ) ;
// 创建文件并写入内容
string filePath = Path . Combine ( folderPath , DbUtil . GenerateClassName ( tbname ) + ".cs" ) ;
File . WriteAllText ( filePath , infoStr ) ;
// 打开文件夹
System . Diagnostics . Process . Start ( folderPath ) ;
}
public static string joinList ( List < string > list )
{
string str = "" ;
foreach ( var item in list )
{
str + = ( str = = "" ? "" : "," ) + "\"" + item + "\"" ;
}
return str ;
}
public static List < Dictionary < string , string > > getTableInfo ( string tbname , string sql = "" )
{
DataTable dt = null ;
if ( sql = = "" )
dt = DbUtil . GetDbTableInfo ( tbname ) ;
else
dt = DbHelperMySQL . Query ( sql ) ;
List < Dictionary < string , string > > filedInfos = new List < Dictionary < string , string > > ( ) ;
for ( int i = 0 ; i < dt . Rows . Count ; i + + )
{
var dict = new Dictionary < string , string > ( ) ;
var Name = dt . Rows [ i ] [ "Name" ] . ToString ( ) ;
var COMMENT = dt . Rows [ i ] [ "COMMENT" ] . ToString ( ) ;
var KeyType = dt . Rows [ i ] [ "KeyType" ] . ToString ( ) ;
var Nullable = dt . Rows [ i ] [ "Nullable" ] . ToString ( ) ;
Type type = DbUtil . DbTypeStr_To_CsharpType ( dt . Rows [ i ] [ "Type" ] . ToString ( ) ) ;
dict [ "sql_field_name" ] = Name ;
dict [ "field_name" ] = DbUtil . ToCamelCase ( Name ) ;
dict [ "type_name" ] = type . Name ;
dict [ "comment" ] = COMMENT ;
dict [ "is_primary_key" ] = ( String . IsNullOrEmpty ( KeyType ) ? "false" : "true" ) ;
dict [ "is_nullable" ] = ( String . IsNullOrEmpty ( KeyType ) & & ! ( "NULL" . Equals ( Nullable ) ) ? "true" : "false" ) ;
filedInfos . Add ( dict ) ;
}
return filedInfos ;
}
public static List < string > getTimeFields ( List < Dictionary < string , string > > filedInfos )
{
var list = new List < string > ( ) ;
filedInfos . ForEach ( info = >
{
if ( info [ "type_name" ] = = "DateTime" ) list . Add ( info [ "sql_field_name" ] ) ;
} ) ;
return list ;
}
/// <summary>
/// 根据参数,获取数据表信息
/// </summary>
/// <param name="tabname"></param>
public static DataTable GetDbTableInfo ( string tabname )
{
string sql = @ "SELECT
c . COLUMN_NAME AS Name ,
c . COLUMN_TYPE AS Type ,
c . COLUMN_COMMENT AS Comment ,
CASE WHEN CONSTRAINT_NAME = ' PRIMARY ' THEN ' PRIMARY KEY ' ELSE ' ' END AS KeyType ,
CASE WHEN c . IS_NULLABLE = ' NO ' THEN ' NOT NULL ' ELSE ' NULL ' END AS Nullable
FROM
INFORMATION_SCHEMA . COLUMNS c
LEFT JOIN
INFORMATION_SCHEMA . KEY_COLUMN_USAGE k
ON
c . TABLE_SCHEMA = k . TABLE_SCHEMA
AND c . TABLE_NAME = k . TABLE_NAME
AND c . COLUMN_NAME = k . COLUMN_NAME
WHERE
c . TABLE_NAME = ' { 0 } '
AND
c . TABLE_SCHEMA = ' { 1 } '
ORDER BY
c . ORDINAL_POSITION ; ";
//string str = $"SELECT COLUMN_NAME AS Name, COLUMN_TYPE AS Type,COLUMN_COMMENT AS COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{tabname}' ORDER BY ORDINAL_POSITION;";
var dt = DbHelperMySQL . Query ( String . Format ( sql , tabname , DbHelperMySQL . DbName ) ) ;
return dt ;
}
public static string GetTableComment ( string tableName )
{
string sql = $"SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}' AND TABLE_NAME ='{tableName}';" ;
var dt = DbHelperMySQL . Query ( sql ) ;
if ( dt . Rows . Count < 1 ) return tableName ;
return dt . Rows [ 0 ] [ "TABLE_COMMENT" ] . ToString ( ) ;
}
public static List < string > GetTableName ( string tableName )
{
string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}' AND TABLE_NAME LIKE '{tableName}%' limit 20;" ;
var dt = DbHelperMySQL . Query ( sql ) ;
//查询数据库表中所有已录入人员
List < string > sList = new List < string > ( ) ; //存放数据库查询结果
for ( int i = 0 ; i < dt . Rows . Count ; i + + )
{
sList . Add ( dt . Rows [ i ] [ "TABLE_NAME" ] . ToString ( ) ) ;
}
return sList ;
//return dt;
}
public static List < string > GetTableName ( )
{
string sql = $"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{DbHelperMySQL.DbName}';" ;
var dt = DbHelperMySQL . Query ( sql ) ;
//查询数据库表中所有已录入人员
List < string > sList = new List < string > ( ) ; //存放数据库查询结果
for ( int i = 0 ; i < dt . Rows . Count ; i + + )
{
sList . Add ( dt . Rows [ i ] [ "TABLE_NAME" ] . ToString ( ) ) ;
}
return sList ;
}
public static List < string > GetDataBaseName ( string dataBaseName = null )
{
string sql = $"SHOW DATABASES {(string.IsNullOrEmpty(dataBaseName) ? "" : $" LIKE ' % { dataBaseName } % ' ")} ;" ;
var dt = DbHelperMySQL . Query ( sql ) ;
//查询数据库表中所有已录入人员
List < string > sList = new List < string > ( ) ; //存放数据库查询结果
for ( int i = 0 ; i < dt . Rows . Count ; i + + )
{
sList . Add ( dt . Rows [ i ] [ $"Database{(string.IsNullOrEmpty(dataBaseName) ? "" : $" ( % { dataBaseName } % ) ")}" ] . ToString ( ) ) ;
}
return sList ;
}
public static Dictionary < string , Type > DbTypeDic { get ; } = new Dictionary < string , Type > ( StringComparer . OrdinalIgnoreCase )
{
{ "int" , typeof ( int ) } ,
{ "integer" , typeof ( int ) } ,
{ "tinyint" , typeof ( byte ) } ,
{ "smallint" , typeof ( short ) } ,
{ "mediumint" , typeof ( int ) } ,
{ "bigint" , typeof ( long ) } ,
{ "float" , typeof ( float ) } ,
{ "double" , typeof ( double ) } ,
{ "decimal" , typeof ( decimal ) } ,
{ "char" , typeof ( string ) } ,
{ "varchar" , typeof ( string ) } ,
{ "text" , typeof ( string ) } ,
{ "mediumtext" , typeof ( string ) } ,
{ "longtext" , typeof ( string ) } ,
{ "enum" , typeof ( string ) } ,
{ "date" , typeof ( DateTime ) } ,
{ "time" , typeof ( TimeSpan ) } ,
{ "datetime" , typeof ( DateTime ) } ,
{ "timestamp" , typeof ( DateTime ) } ,
{ "year" , typeof ( int ) } ,
{ "binary" , typeof ( byte [ ] ) } ,
{ "varbinary" , typeof ( byte [ ] ) } ,
{ "blob" , typeof ( byte [ ] ) } ,
{ "mediumblob" , typeof ( byte [ ] ) } ,
{ "longblob" , typeof ( byte [ ] ) } ,
{ "bit" , typeof ( bool ) } ,
{ "boolean" , typeof ( bool ) } ,
{ "json" , typeof ( string ) } ,
{ "geometry" , typeof ( object ) } , // Geometry 数据类型的映射可能需要特殊处理
// 更多其他数据类型
} ;
/// <summary>
/// 获取字段类型
/// </summary>
/// <param name="dbTypeStr"></param>
/// <returns></returns>
public static Type DbTypeStr_To_CsharpType ( string dbTypeStr )
{
if ( dbTypeStr . Contains ( '(' ) )
{
string [ ] strings = dbTypeStr . Split ( '(' ) ;
dbTypeStr = strings [ 0 ] ;
}
string _dbTypeStr = dbTypeStr . ToLower ( ) ;
Type type = null ;
if ( DbTypeDic . ContainsKey ( _dbTypeStr ) )
type = DbTypeDic [ _dbTypeStr ] ;
else
type = typeof ( string ) ;
return type ;
}
/// <summary>
/// 将数据库字段转换为驼峰命名
/// </summary>
/// <param name="dbField"></param>
/// <returns></returns>
public static string ToCamelCase ( string dbField )
{
string [ ] words = dbField . Split ( '_' ) ;
for ( int i = 1 ; i < words . Length ; i + + )
{
words [ i ] = char . ToUpper ( words [ i ] [ 0 ] ) + words [ i ] . Substring ( 1 ) ;
}
return string . Join ( "" , words ) ;
}
// 根据数据库表名生成实体类名称
public static string GenerateClassName ( string tableName )
{
string [ ] words = tableName . Split ( '_' ) ;
StringBuilder sb = new StringBuilder ( ) ;
foreach ( string word in words )
{
sb . Append ( CultureInfo . CurrentCulture . TextInfo . ToTitleCase ( word . ToLower ( ) ) ) ;
}
return sb . ToString ( ) ;
}
/ * /// <summary>
/// 类型转换枚举
/// </summary>
protected Dictionary < string , Type > DbTypeDic { get ; } = new Dictionary < string , Type > ( )
{
{ "int" , typeof ( Int32 ) } ,
{ "text" , typeof ( string ) } ,
{ "enum" , typeof ( string ) } ,
{ "bigint" , typeof ( Int64 ) } ,
{ "binary" , typeof ( byte [ ] ) } ,
{ "bit" , typeof ( bool ) } ,
{ "char" , typeof ( string ) } ,
{ "date" , typeof ( DateTime ) } ,
{ "datetime" , typeof ( DateTime ) } ,
{ "datetime2" , typeof ( DateTime ) } ,
{ "decimal" , typeof ( decimal ) } ,
{ "float" , typeof ( double ) } ,
{ "image" , typeof ( byte [ ] ) } ,
{ "money" , typeof ( decimal ) } ,
{ "nchar" , typeof ( string ) } ,
{ "ntext" , typeof ( string ) } ,
{ "numeric" , typeof ( decimal ) } ,
{ "nvarchar" , typeof ( string ) } ,
{ "real" , typeof ( Single ) } ,
{ "smalldatetime" , typeof ( DateTime ) } ,
{ "smallint" , typeof ( Int16 ) } ,
{ "smallmoney" , typeof ( decimal ) } ,
{ "timestamp" , typeof ( DateTime ) } ,
{ "tinyint" , typeof ( bool ) } ,
{ "varbinary" , typeof ( byte [ ] ) } ,
{ "varchar" , typeof ( string ) } ,
{ "variant" , typeof ( object ) } ,
{ "uniqueidentifier" , typeof ( Guid ) } ,
} ;
/// <summary>
/// 获取字段类型
/// </summary>
/// <param name="dbTypeStr"></param>
/// <returns></returns>
public virtual Type DbTypeStr_To_CsharpType ( string dbTypeStr )
{
if ( dbTypeStr . Contains ( '(' ) )
{
string [ ] strings = dbTypeStr . Split ( '(' ) ;
dbTypeStr = strings [ 0 ] ;
}
string _dbTypeStr = dbTypeStr . ToLower ( ) ;
Type type = null ;
if ( DbTypeDic . ContainsKey ( _dbTypeStr ) )
type = DbTypeDic [ _dbTypeStr ] ;
else
type = typeof ( string ) ;
return type ;
}
* /
}
}