-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSQLQuery.cs
More file actions
247 lines (216 loc) · 8.71 KB
/
SQLQuery.cs
File metadata and controls
247 lines (216 loc) · 8.71 KB
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
242
243
244
245
246
247
using ScriptEngine.Machine.Contexts;
using ScriptEngine.Machine;
using ScriptEngine.HostedScript.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
using MySql.Data.MySqlClient;
using Npgsql;
namespace OScriptSql
{
/// <summary>
/// Предназначен для выполнения запросов к базе данных.
/// </summary>
[ContextClass("Запрос", "Query")]
public class Query : AutoContext<Query>, IOScriptQuery
{
private string _text;
private DbConnection _connection;
private DbCommand _command;
private StructureImpl _parameters;
private DBConnector _connector;
public Query()
{
_parameters = new StructureImpl();
_text = "";
}
[ScriptConstructor]
public static IRuntimeContextInstance Constructor()
{
return new Query();
}
[ContextProperty("Параметры", "Parameters")]
public StructureImpl Parameters
{
get { return _parameters; }
}
/// <summary>
/// Управление таймауотом
/// </summary>
/// <value>Число</value>
[ContextProperty("Таймаут", "Timeout")]
public int Timeout
{
get { return _command.CommandTimeout; }
set
{
_command.CommandTimeout = value;
}
}
/// <summary>
/// Содержит исходный текст выполняемого запроса.
/// </summary>
/// <value>Строка</value>
[ContextProperty("Текст", "Text")]
public string Text
{
get { return _text; }
set
{
_text = value;
}
}
private void setDbCommandParameters()
{
DbParameter param = null;
foreach (IValue prm in _parameters)
{
var paramVal = ((KeyAndValueImpl)prm).Value;
var paramKey = ((KeyAndValueImpl)prm).Key.AsString();
if (paramVal.DataType == DataType.String)
{
param = _command.CreateParameter();
param.ParameterName = "@" + paramKey;
param.Value = paramVal.AsString();
}
else if (paramVal.DataType == DataType.Number)
{
param = _command.CreateParameter();
param.ParameterName = "@" + paramKey;
param.Value = paramVal.AsNumber();
}
else if (paramVal.DataType == DataType.Date)
{
param = _command.CreateParameter();
param.ParameterName = "@" + paramKey;
param.Value = paramVal.AsDate();
}
else if (paramVal.DataType == DataType.Boolean)
{
param = _command.CreateParameter();
param.ParameterName = "@" + paramKey;
param.Value = paramVal.AsBoolean();
}
_command.Parameters.Add(param);
}
}
/// <summary>
/// Выполняет запрос к базе данных.
/// </summary>
/// <returns>РезультатЗапроса</returns>
[ContextMethod("Выполнить", "Execute")]
public IValue Execute()
{
var result = new QueryResult();
DbDataReader reader = null;
_command.Parameters.Clear();
_command.CommandText = _text;
setDbCommandParameters();
reader = _command.ExecuteReader();
result = new QueryResult(reader);
return result;
}
/// <summary>
/// Выполняет запрос к базе данных. Cиноним для Выполнить
/// </summary>
/// <returns>РезультатЗапроса</returns>
[ContextMethod("ВыполнитьЗапрос", "ExecuteQuery")]
public IValue ExecuteQuery()
{
return Execute();
}
/// <summary>
/// Выполняет запрос на модификацию к базе данных.
/// </summary>
/// <returns>Число - Число обработанных строк.</returns>
[ContextMethod("ВыполнитьКоманду", "ExecuteCommand")]
public int ExecuteCommand()
{
var sec = new SystemEnvironmentContext();
string versionOnescript = sec.Version;
string[] verInfo = versionOnescript.Split('.');
//if (Convert.ToInt64(verInfo[2]) >= 15)
//{
// Console.WriteLine("> 15");
//}
var result = new QueryResult();
_command.Parameters.Clear();
_command.CommandText = _text;
setDbCommandParameters();
return _command.ExecuteNonQuery();
}
/// <summary>
/// Устанавливает параметр запроса. Параметры доступны для обращения в тексте запроса.
/// С помощью этого метода можно передавать переменные в запрос, например, для использования в условиях запроса.
/// ВАЖНО: В запросе имя параметра указывается с использованием '@'.
/// </summary>
/// <example>
/// Запрос.Текст = "select * from mytable where category_id = @category_id";
/// Запрос.УстановитьПараметр("category_id", 1);
/// </example>
/// <param name="ParametrName">Строка - Имя параметра</param>
/// <param name="ParametrValue">Произвольный - Значение параметра</param>
[ContextMethod("УстановитьПараметр", "SetParameter")]
public void SetParameter(string ParametrName, IValue ParametrValue)
{
_parameters.Insert(ParametrName, ParametrValue);
}
/// <summary>
/// Установка соединения с БД.
/// </summary>
/// <param name="connector">Соединение - объект соединение с БД</param>
[ContextMethod("УстановитьСоединение", "SetConnection")]
public void SetConnection(DBConnector connector)
{
_connector = connector;
_connection = connector.Connection;
if (_connector.DbType == (new EnumDBType()).sqlite)
{
_command = new SQLiteCommand((SQLiteConnection)connector.Connection);
}
else if (_connector.DbType == (new EnumDBType()).MSSQLServer)
{
_command = new SqlCommand();
_command.Connection = (SqlConnection)connector.Connection;
}
else if (_connector.DbType == (new EnumDBType()).MySQL)
{
_command = new MySqlCommand();
_command.Connection = (MySqlConnection)connector.Connection;
}
else if (_connector.DbType == (new EnumDBType()).PostgreSQL)
{
_command = new NpgsqlCommand();
_command.Connection = (NpgsqlConnection)connector.Connection;
}
}
[ContextMethod("ИДПоследнейДобавленнойЗаписи", "LastInsertRowId")]
public int LastInsertRowId()
{
if (_connector.DbType == (new EnumDBType()).sqlite)
{
return (int)((SQLiteConnection)_connection).LastInsertRowId;
}
else if (_connector.DbType == (new EnumDBType()).MSSQLServer)
{
return -1;
}
else if (_connector.DbType == (new EnumDBType()).MySQL)
{
return (int)((MySqlCommand)_command).LastInsertedId;
}
else if (_connector.DbType == (new EnumDBType()).PostgreSQL)
{
return -1;
}
return -1;
}
}
}