ningshuxia
2024-05-06 8f6d2b48f22b695574bd4a6c4ac91b1ac9f780b1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
using System.Threading.Tasks;
using System.Xml.Linq;
 
namespace IStation.DAL
{
    /// <summary>
    ///   
    /// </summary>
    public class ScheduleCombine_bak
    {
        public SqlSugarClient Connection
        {
            get { return ConfigHelper.GetSqlSugarClient(); }
        }
 
        private readonly string _tableNamePrefix = "ScheduleCombine_Cb_";
 
        private string GetTableName(string runFlag)
        {
            return $"{_tableNamePrefix}{runFlag}";
        }
 
        private readonly string _createTable = "(\r\n    ID        BIGINT        NOT NULL\r\n                            PRIMARY KEY,\r\n    RunFlag   VARCHAR (255),\r\n    RunCount  INTEGER,\r\n    Pump1     REAL,\r\n    Pump2     REAL,\r\n    Pump3     REAL,\r\n    CurveQH   VARCHAR (255),\r\n    CurveQP   VARCHAR (255),\r\n    MaxFlow   REAL,\r\n    MinFlow   REAL,\r\n    MaxHead   REAL,\r\n    MinHead   REAL,\r\n    AnaStatus BIT\r\n);";
 
        /// <summary>
        /// 获取全部表名
        /// </summary>
        public List<string> GetAllTableName()
        {
            var tables = new List<string>();
            using (var connection = new SQLiteConnection(ConfigHelper.ConnectionString))
            {
                connection.Open();
                var sql = $"select name from sqlite_master where type='table' and name like '%{_tableNamePrefix}%';";
                using (var command = new SQLiteCommand(sql, connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var tableName = reader["name"].ToString();
                            tables.Add(tableName);
                        }
                    }
                }
            }
            return tables;
        }
 
 
        /// <summary>
        /// 通过表名获取所有未分析组合
        /// </summary>
        public List<Entity.ScheduleCombine> GetAllUnanalyzedAnaByTableName(string tableName)
        {
            using (SqlSugarClient db = Connection)
            {
                var sql = $"select * from {tableName} where AnaStatus=False";
                var list = db.Ado.SqlQuery<Entity.ScheduleCombine>(sql);
                return list;
            }
        }
 
 
        /// <summary>
        /// 大批量插入
        /// </summary>
        public bool BulkInserts_SplitTable(List<Entity.ScheduleCombine> list)
        {
            if (list == null || list.Count < 1)
                return default;
            using (SqlSugarClient db = Connection)
            {
                ///自己来制定定义的规则
                db.CurrentConnectionConfig.ConfigureExternalServices.SplitTableService = new Entity.ScheduleCombineSubTableService();
                db.CodeFirst
                    .SplitTables()//标识分表
                    .InitTables<Entity.ScheduleCombine>(); //程序启动时加这一行,如果一张表没有会初始化一张
 
                //大数据写入+表不存在会建表
                //自动找表大数据写入 
                return db.Fastest<Entity.ScheduleCombine>().SplitTable().BulkCopy(list) > 0;
            }
        }
 
 
 
        /// <summary>
        /// 大批量插入
        /// </summary>
        public async Task<bool> BulkInserts_Create_Async(string runFlag, List<Entity.ScheduleCombine> list)
        {
            if (list == null || list.Count < 1)
                return default;
            var tableName = GetTableName(runFlag);
            using (SqlSugarClient db = Connection)
            {
                var exist_sql = $"select count(*)  from sqlite_master where type = 'table' and name = '{tableName}' ;";
                if (db.Ado.GetInt(exist_sql) < 1)
                {
                    var sql_create_table = $"CREATE TABLE {tableName} {_createTable}";
                    if (db.Ado.ExecuteCommand(sql_create_table) < 1)
                    {
                        return false;
                    }
                }
                return await db.Fastest<Entity.ScheduleCombine>().AS(tableName).BulkCopyAsync(list) > 0;
            }
        }
 
 
        /// <summary>
        /// 大批量插入
        /// </summary>
        public bool BulkInserts_Create(string runFlag, List<Entity.ScheduleCombine> list)
        {
            if (list == null || list.Count < 1)
                return default;
            var tableName = GetTableName(runFlag);
            using (SqlSugarClient db = Connection)
            {
                var exist_sql = $"select count(*)  from sqlite_master where type = 'table' and name = '{tableName}';";
                if (db.Ado.ExecuteCommand(exist_sql) < 1)
                {
                    var sql_create_table = $"CREATE TABLE {tableName} {_createTable}";
                    db.Ado.ExecuteCommand(sql_create_table);
                }
                //大数据写入
                return db.Fastest<Entity.ScheduleCombine>().AS(tableName).BulkCopy(list) > 0;
            }
        }
 
        /// <summary>
        /// 大批量插入
        /// </summary> 
        public bool BulkInserts_NativeSql(string runFlag, List<Entity.ScheduleCombine> list)
        {
            var tableName = GetTableName(runFlag);
            var connect = ConfigHelper.ConnectionString;
            SQLiteConnection connection = new SQLiteConnection(connect);//连接对象初始化 
            connection.Open();//打开连接
 
            SQLiteCommand command = new SQLiteCommand(connection);//命令对象初始化 
            command.CommandText = $"VACUUM;";//执行VACUUM命令收缩数据库
            command.ExecuteNonQuery();
 
            SQLiteTransaction transaction = connection.BeginTransaction();//开始事务 
            var sql_exist_table = $"select count(*)  from sqlite_master where type = 'table' and name = '{tableName}';";
            command.CommandText = sql_exist_table;
            if (command.ExecuteNonQuery() < 1)//没有表就创建表
            {
                var sql_create_table = $"CREATE TABLE {tableName} (\r\n    ID        BIGINT        NOT NULL\r\n                            PRIMARY KEY,\r\n    RunFlag   VARCHAR (255),\r\n    RunCount  INTEGER,\r\n    Pump1     REAL,\r\n    Pump2     REAL,\r\n    Pump3     REAL,\r\n    CurveQH   VARCHAR (255),\r\n    CurveQP   VARCHAR (255),\r\n    AnaStatus BIT\r\n);";
                command.CommandText = sql_create_table;
                command.ExecuteNonQuery();
            }
 
            var group = list.GroupBy(x => x.ID).Where(x => x.Count() > 1).Count();
 
            for (int i = 0; i < list.Count; i++) //[---使用事务---]执行INSERT命令
            {
                var item = list[i];
                var sql_insert = $"INSERT INTO {tableName}(ID, RunFlag, RunCount, Pump1, Pump2, Pump3, CurveQH, CurveQP, AnaStatus) " +
                    $"VALUES ('{item.ID}','{item.RunFlag}','{item.RunCount}','{item.Pump1}','{item.Pump2}','{item.Pump3}','{item.CurveQH}','{item.CurveQP}','{item.AnaStatus}')";
                command.CommandText = sql_insert;
                command.ExecuteNonQuery();
            }
            // var result = command.ExecuteScalar();
            transaction.Commit();//提交事务
            connection.Close();//关闭连接 
            return true;
        }
 
 
        /// <summary>
        /// 设置已分析状态
        /// </summary>
        public bool SetAnaStatus(string tableName, long id)
        {
            using (SqlSugarClient db = Connection)
            {
                var sql = $"update {tableName} set AnaStatus=True where ID={id}";
                var bol = db.Ado.ExecuteCommand(sql) > 0;
                return bol;
            }
        }
 
 
        /// <summary>
        /// 设置已分析状态
        /// </summary>
        public bool SetAnaStatus(string tableName, List<long> ids)
        {
            using (SqlSugarClient db = Connection)
            {
                var sql = $"update {tableName} set AnaStatus=True where ID in(@ids)";
                var obj = new { ids = ids.ToArray() };
                var bol = db.Ado.ExecuteCommand(sql, obj) > 0;
                return bol;
            }
        }
 
 
        /// <summary>
        /// 判断数据库是否存在表
        /// </summary> 
        public bool ExistTable(string runFlag)
        {
            using (SqlSugarClient db = Connection)
            {
                var sql = $"select count(*)  from sqlite_master where type = 'table' and name = '{GetTableName(runFlag)}';";
                var bol = db.Ado.ExecuteCommand(sql) > 0;
                return bol;
            }
        }
 
        /// <summary>
        /// 获取全部表名
        /// </summary>
        public bool DeleteAllTable()
        {
            var tables = GetAllTableName();
            if (tables == null || !tables.Any())
                return false;
 
            using (SqlSugarClient db = Connection)
            {
                db.BeginTran();
 
                foreach (var table in tables)
                {
                    var sql = $"drop table {table};";
                    db.Ado.ExecuteCommand(sql);
                }
                db.CommitTran();
            }
            return true;
        }
 
 
    }
}