/
AdoAdapterInserter.cs
93 lines (81 loc) · 3.08 KB
/
AdoAdapterInserter.cs
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
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
namespace Simple.Data.Ado
{
class AdoAdapterInserter
{
private readonly AdoAdapter _adapter;
public AdoAdapterInserter(AdoAdapter adapter)
{
_adapter = adapter;
}
public IDictionary<string, object> Insert(string tableName, IDictionary<string, object> data)
{
var table = _adapter.GetSchema().FindTable(tableName);
string columnList =
data.Keys.Select(s => table.FindColumn(s).QuotedName).Aggregate((agg, next) => agg + "," + next);
string valueList = data.Keys.Select(s => "?").Aggregate((agg, next) => agg + "," + next);
string insertSql = "insert into " + table.QuotedName + " (" + columnList + ") values (" + valueList + ")";
var identityColumn = table.Columns.FirstOrDefault(col => col.IsIdentity);
if (identityColumn != null)
{
insertSql += "; select * from " + table.QuotedName + " where " + identityColumn.QuotedName +
" = scope_identity()";
return ExecuteSingletonQuery(insertSql, data.Values.ToArray());
}
Execute(insertSql, data.Values.ToArray());
return null;
}
internal IDictionary<string, object> ExecuteSingletonQuery(string sql, params object[] values)
{
using (var connection = _adapter.CreateConnection())
{
using (var command = CommandHelper.Create(connection, sql, values.ToArray()))
{
try
{
connection.Open();
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
return reader.ToDictionary();
}
}
}
catch (DbException ex)
{
throw new AdoAdapterException(ex.Message, command);
}
}
}
return null;
}
internal int Execute(string sql, params object[] values)
{
using (var connection = _adapter.CreateConnection())
{
using (var command = CommandHelper.Create(connection, sql, values.ToArray()))
{
return TryExecute(connection, command);
}
}
}
private static int TryExecute(DbConnection connection, IDbCommand command)
{
try
{
connection.Open();
return command.ExecuteNonQuery();
}
catch (DbException ex)
{
throw new AdoAdapterException(ex.Message, command);
}
}
}
}