Browse Source

数据库链接工具

yuzhengyang 3 years ago
parent
commit
64944e913e

+ 4 - 0
Azylee.Utils/Azylee.Core/Azylee.Core.csproj

@@ -66,6 +66,8 @@
     <Compile Include="DataUtils\CollectionUtils\Ls.cs" />
     <Compile Include="DataUtils\CompressionUtils\Compression.cs" />
     <Compile Include="DataUtils\CurrencyUtils\RMB.cs" />
+    <Compile Include="DataUtils\DataTableUtils\DataRowTool.cs" />
+    <Compile Include="DataUtils\DataTableUtils\DataTableTool.cs" />
     <Compile Include="DataUtils\DateTimeUtils\ChineseHourTool.cs" />
     <Compile Include="DataUtils\DateTimeUtils\DateTimeFormatter.cs" />
     <Compile Include="DataUtils\DateTimeUtils\DateTimeConvert.cs" />
@@ -88,12 +90,14 @@
     <Compile Include="DataUtils\StringUtils\Str.cs" />
     <Compile Include="DataUtils\StringUtils\StringArrayTool.cs" />
     <Compile Include="DataUtils\StringUtils\StringExtension.cs" />
+    <Compile Include="DataUtils\StringUtils\StringFinder.cs" />
     <Compile Include="DataUtils\StringUtils\StringGenerator.cs" />
     <Compile Include="DataUtils\StringUtils\StringTool.cs" />
     <Compile Include="DataUtils\UnitConvertUtils\ByteConvertTool.cs" />
     <Compile Include="DbUtils\DbModels\DatabaseType.cs" />
     <Compile Include="DbUtils\DbInterface\IDatabaseHelper.cs" />
     <Compile Include="DbUtils\DbSqls\DbSqlTool.cs" />
+    <Compile Include="DbUtils\DbSqls\SqlGenerate.cs" />
     <Compile Include="DelegateUtils\ProcessDelegateUtils\ProgressDelegate.cs" />
     <Compile Include="DelegateUtils\ProcessDelegateUtils\ProgressEventArgs.cs" />
     <Compile Include="DllUtils\DllInvokeTool.cs" />

+ 80 - 1
Azylee.Utils/Azylee.DB/Azylee.DB.csproj

@@ -9,8 +9,9 @@
     <AppDesignerFolder>Properties</AppDesignerFolder>
     <RootNamespace>Azylee.DB</RootNamespace>
     <AssemblyName>Azylee.DB</AssemblyName>
-    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
+    <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
@@ -20,6 +21,7 @@
     <DefineConstants>DEBUG;TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <Prefer32Bit>false</Prefer32Bit>
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
     <DebugType>pdbonly</DebugType>
@@ -28,23 +30,100 @@
     <DefineConstants>TRACE</DefineConstants>
     <ErrorReport>prompt</ErrorReport>
     <WarningLevel>4</WarningLevel>
+    <Prefer32Bit>false</Prefer32Bit>
   </PropertyGroup>
   <ItemGroup>
+    <Reference Include="BouncyCastle.Crypto, Version=1.9.0.0, Culture=neutral, PublicKeyToken=0e99375e54769942, processorArchitecture=MSIL">
+      <HintPath>..\packages\Portable.BouncyCastle.1.9.0\lib\net40\BouncyCastle.Crypto.dll</HintPath>
+    </Reference>
+    <Reference Include="Google.Protobuf, Version=3.19.4.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604, processorArchitecture=MSIL">
+      <HintPath>..\packages\Google.Protobuf.3.19.4\lib\net45\Google.Protobuf.dll</HintPath>
+    </Reference>
+    <Reference Include="K4os.Compression.LZ4, Version=1.2.6.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
+      <HintPath>..\packages\K4os.Compression.LZ4.1.2.6\lib\net46\K4os.Compression.LZ4.dll</HintPath>
+    </Reference>
+    <Reference Include="K4os.Compression.LZ4.Streams, Version=1.2.6.0, Culture=neutral, PublicKeyToken=2186fa9121ef231d, processorArchitecture=MSIL">
+      <HintPath>..\packages\K4os.Compression.LZ4.Streams.1.2.6\lib\net46\K4os.Compression.LZ4.Streams.dll</HintPath>
+    </Reference>
+    <Reference Include="K4os.Hash.xxHash, Version=1.0.6.0, Culture=neutral, PublicKeyToken=32cd54395057cec3, processorArchitecture=MSIL">
+      <HintPath>..\packages\K4os.Hash.xxHash.1.0.6\lib\net46\K4os.Hash.xxHash.dll</HintPath>
+    </Reference>
+    <Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.1.1.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
+    </Reference>
+    <Reference Include="MySql.Data, Version=8.0.30.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
+      <HintPath>..\packages\MySql.Data.8.0.30\lib\net452\MySql.Data.dll</HintPath>
+    </Reference>
+    <Reference Include="Npgsql, Version=4.1.12.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7, processorArchitecture=MSIL">
+      <HintPath>..\packages\Npgsql.4.1.12\lib\net461\Npgsql.dll</HintPath>
+    </Reference>
     <Reference Include="System" />
+    <Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
+    </Reference>
+    <Reference Include="System.ComponentModel, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
+    <Reference Include="System.ComponentModel.DataAnnotations" />
+    <Reference Include="System.Configuration" />
+    <Reference Include="System.Configuration.Install" />
     <Reference Include="System.Core" />
+    <Reference Include="System.Management" />
+    <Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Numerics" />
+    <Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Text.Encodings.Web, Version=4.0.4.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Text.Encodings.Web.4.6.0\lib\netstandard2.0\System.Text.Encodings.Web.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Text.Json, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Text.Json.4.6.0\lib\net461\System.Text.Json.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.3\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll</HintPath>
+    </Reference>
+    <Reference Include="System.Transactions" />
+    <Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
+      <HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
+    </Reference>
     <Reference Include="System.Xml.Linq" />
     <Reference Include="System.Data.DataSetExtensions" />
     <Reference Include="Microsoft.CSharp" />
     <Reference Include="System.Data" />
     <Reference Include="System.Xml" />
+    <Reference Include="Ubiety.Dns.Core, Version=2.2.1.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
+      <HintPath>..\packages\MySql.Data.8.0.30\lib\net452\Ubiety.Dns.Core.dll</HintPath>
+    </Reference>
+    <Reference Include="ZstdNet, Version=1.4.5.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
+      <HintPath>..\packages\MySql.Data.8.0.30\lib\net452\ZstdNet.dll</HintPath>
+    </Reference>
   </ItemGroup>
   <ItemGroup>
     <Compile Include="DAO\DbTable.cs" />
     <Compile Include="DAO\IDbContext.cs" />
     <Compile Include="DAO\Muse.cs" />
     <Compile Include="DAO\SuperDb.cs" />
+    <Compile Include="DbFactory\DbFactory.cs" />
+    <Compile Include="DbHelper\PgSqls\PgSqlDatabaseHelper.cs" />
     <Compile Include="Migrations\MigraConf.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>
+  <ItemGroup>
+    <None Include="app.config" />
+    <None Include="packages.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <Folder Include="DbHelper\Mysqls\" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\Azylee.Core\Azylee.Core.csproj">
+      <Project>{88DC61FA-95F0-41B7-9D7D-AB0F3CBD169C}</Project>
+      <Name>Azylee.Core</Name>
+    </ProjectReference>
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
 </Project>

+ 27 - 0
Azylee.Utils/Azylee.DB/DbFactory/DbFactory.cs

@@ -0,0 +1,27 @@
+using Azylee.Core.AppUtils.AppConfigUtils.AppConfigModels;
+using Azylee.Core.DbUtils.DbInterface;
+using Azylee.Core.DbUtils.DbModels;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Azylee.DB.DbFactory
+{
+    public class DbFactory
+    {
+        //public static IDatabaseHelper create(AppConfigDbItem config, string database = null)
+        //{
+        //    switch (config.DbType())
+        //    {
+        //        case DatabaseType.PostgreSQL:
+        //            return new PgSqlDatabaseHelper(config, database);
+
+        //        case DatabaseType.Mysql:
+        //        default:
+        //            return new MySqlDatabaseHelper(config, database);
+        //    }
+        //}
+    }
+}

+ 194 - 0
Azylee.Utils/Azylee.DB/DbHelper/PgSqls/PgSqlDatabaseHelper.cs

@@ -0,0 +1,194 @@
+using Azylee.Core.AppUtils.AppConfigUtils.AppConfigModels;
+using Azylee.Core.DataUtils.CollectionUtils;
+using Azylee.Core.DbUtils.DbInterface;
+using Azylee.Core.IOUtils.TxtUtils;
+using Npgsql;
+using System;
+using System.Collections.Generic;
+using System.Data;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Azylee.DB.DbHelper.PgSqls
+
+{
+    public class PgSqlDatabaseHelper : IDatabaseHelper, IDisposable
+    {
+        private AppConfigDbItem Config;
+        private string Database;
+
+        private NpgsqlConnection dbConn = null;
+        private NpgsqlCommand dbCmd = null;
+        private NpgsqlDataReader dbDataReader = null;
+
+        public PgSqlDatabaseHelper(AppConfigDbItem _config, string _database)
+        {
+            Config = _config;
+            Database = _database;
+
+            // 处理扩展参数
+            if (Config.CommandTimeout > 0) Config.JoinConnectString = $"CommandTimeout={Config.CommandTimeout};" + Config.JoinConnectString;
+            else Config.JoinConnectString = $"CommandTimeout=1800;" + Config.JoinConnectString;
+
+
+            if (OpenConnect()) { }
+            else
+            {
+                //ToastForm.Display("数据库连接失败", "未能打开当前数据连接,请检查地址和数据库是否选择正确", ToastForm.ToastType.error);
+            }
+        }
+
+
+        public bool OpenConnect()
+        {
+            try
+            {
+                dbConn = new NpgsqlConnection(Config.ConnectionString(Database));
+                dbCmd = new NpgsqlCommand();
+
+                dbCmd.Connection = dbConn;
+
+                dbConn.Open();
+                return true;
+            }
+            catch (Exception ex)
+            {
+                return false;
+            }
+        }
+
+        public bool TestConnect()
+        {
+            DataTable table = Select(Config.ValidationQuery());
+            if (table != null && table.Rows != null && table.Rows.Count > 0) return true;
+            return false;
+
+        }
+        public DataTable SchemaList()
+        {
+            return Select(Config.SchemaQuery());
+        }
+
+        public DataTable SelectWithException(string sql)
+        {
+            DataTable result = new DataTable();
+            dbCmd.CommandText = sql;
+            NpgsqlDataReader dataReader = dbCmd.ExecuteReader();
+
+            if (dataReader != null)
+            {
+                result.Load(dataReader);
+                dataReader.Close();
+                return result;
+            }
+            return null;
+        }
+
+        public DataTable Select(string sql)
+        {
+            DataTable result = new DataTable();
+            NpgsqlDataReader dataReader = ExecuteReader(sql);
+            if (dataReader != null)
+            {
+                result.Load(dataReader);
+                dataReader.Close();
+                return result;
+            }
+            return null;
+        }
+
+        public NpgsqlDataReader ExecuteReader(string sql)
+        {
+            try
+            {
+                dbCmd.CommandText = sql;
+                dbDataReader = dbCmd.ExecuteReader();
+                return dbDataReader;
+            }
+            catch (Exception ex)
+            {
+                //ToastForm.Display("数据库查询失败", ex.Message, ToastForm.ToastType.error);
+                return null;
+            }
+        }
+
+        public Tuple<bool, int, string> ExecuteFile(string SqlFile, Action<string, bool, int, string> action)
+        {
+            if (!File.Exists(SqlFile)) return new Tuple<bool, int, string>(false, 100, "文件不存在");
+            if (!Path.GetExtension(SqlFile).Contains("sql")) return new Tuple<bool, int, string>(false, 200, "文件格式不正确");
+
+            List<string> lines = TxtTool.ReadLine(SqlFile);
+            if (!Ls.ok(lines)) return new Tuple<bool, int, string>(false, 300, "文件为空");
+
+            StringBuilder sql = new StringBuilder();
+            foreach (var line in lines) { sql.AppendLine(line); }
+
+            // 执行语句
+            Tuple<bool, int, string> flag = ExecuteFileSql(sql.ToString());
+            action.Invoke(sql.ToString(), flag.Item1, flag.Item2, flag.Item3);
+
+            if (!flag.Item1)
+            {
+                return new Tuple<bool, int, string>(false, 400, "异常中断");
+            }
+
+            return new Tuple<bool, int, string>(true, 0, "运行完毕");
+        }
+        private Tuple<bool, int, string> ExecuteFileSql(string sql)
+        {
+            try
+            {
+
+                if (dbConn.State.Equals(ConnectionState.Closed))
+                {
+                    OpenConnect();
+                }
+
+                int flag = 0;
+                using (var cmd = new NpgsqlCommand())
+                {
+                    cmd.Connection = dbConn;
+                    cmd.CommandText = sql;
+                    try
+                    {
+                        flag = cmd.ExecuteNonQuery();
+                    }
+                    catch (Exception ex)
+                    {
+                        //Commons.Log.e(ex.InnerException);
+                        return new Tuple<bool, int, string>(false, 0, ex.Message);
+                    }
+                }
+                return new Tuple<bool, int, string>(true, flag, "");
+            }
+            catch (PostgresException ex)
+            {
+                return new Tuple<bool, int, string>(false, 0, ex.Message + " Hint: " + ex.Hint ?? "");
+            }
+
+        }
+        public int ExecuteNonQuery(string sqlStr_Insert)
+        {
+            dbCmd.CommandText = sqlStr_Insert;
+            int result = dbCmd.ExecuteNonQuery();
+
+            return result;
+        }
+        public void Dispose()
+        {
+            dbConn?.Close();
+        }
+
+        public DataTable ColumnList(string database, string schema, string table)
+        {
+            throw new NotImplementedException();
+        }
+
+        ~PgSqlDatabaseHelper()
+        {
+            dbConn?.Close();
+        }
+    }
+}

+ 27 - 0
Azylee.Utils/Azylee.DB/app.config

@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+  <runtime>
+    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
+      <dependentAssembly>
+        <assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
+      </dependentAssembly>
+      <dependentAssembly>
+        <assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
+        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
+      </dependentAssembly>
+    </assemblyBinding>
+  </runtime>
+</configuration>

+ 19 - 0
Azylee.Utils/Azylee.DB/packages.config

@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="Google.Protobuf" version="3.19.4" targetFramework="net462" />
+  <package id="K4os.Compression.LZ4" version="1.2.6" targetFramework="net462" />
+  <package id="K4os.Compression.LZ4.Streams" version="1.2.6" targetFramework="net462" />
+  <package id="K4os.Hash.xxHash" version="1.0.6" targetFramework="net462" />
+  <package id="Microsoft.Bcl.AsyncInterfaces" version="1.1.0" targetFramework="net462" />
+  <package id="MySql.Data" version="8.0.30" targetFramework="net462" />
+  <package id="Npgsql" version="4.1.12" targetFramework="net462" />
+  <package id="Portable.BouncyCastle" version="1.9.0" targetFramework="net462" />
+  <package id="System.Buffers" version="4.5.1" targetFramework="net462" />
+  <package id="System.Memory" version="4.5.4" targetFramework="net462" />
+  <package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net462" />
+  <package id="System.Runtime.CompilerServices.Unsafe" version="5.0.0" targetFramework="net462" />
+  <package id="System.Text.Encodings.Web" version="4.6.0" targetFramework="net462" />
+  <package id="System.Text.Json" version="4.6.0" targetFramework="net462" />
+  <package id="System.Threading.Tasks.Extensions" version="4.5.3" targetFramework="net462" />
+  <package id="System.ValueTuple" version="4.5.0" targetFramework="net462" />
+</packages>