Skip to content

Commit 3cfaef5

Browse files
committed
#增加mysql数据支撑 表别名设置#
1 parent 7d6b96b commit 3cfaef5

File tree

7 files changed

+89
-29
lines changed

7 files changed

+89
-29
lines changed

APIJSON.NET/APIJSON.NET/APIJSON.NET.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
<PackageReference Include="Dapper" Version="1.50.5" />
1313
<PackageReference Include="Dapper.SqlBuilder" Version="1.50.5" />
1414
<PackageReference Include="Microsoft.AspNetCore.App" />
15+
<PackageReference Include="MySql.Data" Version="8.0.11" />
1516
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.5.0" />
1617
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="2.5.0" />
1718
</ItemGroup>

APIJSON.NET/APIJSON.NET/Controllers/ValuesController.cs

+18-17
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@
1212
[ApiController]
1313
public class JsonController : ControllerBase
1414
{
15-
private DapperOptions _options;
16-
public JsonController(IOptions<DapperOptions> options)
15+
private DapperHelper db;
16+
private JsonToSql sqlbuilder;
17+
public JsonController(DapperHelper helper, JsonToSql jsonToSql)
1718
{
18-
this._options = options.Value;
19+
db = helper;
20+
sqlbuilder = jsonToSql;
1921
}
20-
2122
/// <summary>
2223
/// 查询
2324
/// </summary>
@@ -54,8 +55,8 @@ public ActionResult Query([FromBody]string json)
5455
if (tables.Count > 0)
5556
{
5657
string table = tables[0];
57-
var template = JsonToSql.GetSqlBuilder(table, page, count, where[0], null);
58-
foreach (var dd in DapperDBHelp.Query(_options.ConnectionString, template.RawSql, template.Parameters))
58+
var template = sqlbuilder.GetSqlBuilder(table, page, count, where[0], null);
59+
foreach (var dd in db.Query(template.RawSql, template.Parameters))
5960
{
6061
var zht = new JObject();
6162
zht.Add(table, JToken.FromObject(dd));
@@ -69,18 +70,18 @@ public ActionResult Query([FromBody]string json)
6970
var jbb = JObject.Parse(where[i]);
7071
page = jbb["page"] == null ? 0 : int.Parse(jbb["page"].ToString());
7172
count = jbb["count"] == null ? 0 : int.Parse(jbb["count"].ToString());
72-
template = JsonToSql.GetSqlBuilder(subtable, page, count, jbb[subtable].ToString(), zht);
73+
template = sqlbuilder.GetSqlBuilder(subtable, page, count, jbb[subtable].ToString(), zht);
7374
var lt = new JArray();
74-
foreach (var d in DapperDBHelp.Query(_options.ConnectionString, template.RawSql, template.Parameters))
75+
foreach (var d in db.Query( template.RawSql, template.Parameters))
7576
{
7677
lt.Add(JToken.FromObject(d));
7778
}
7879
zht.Add(tables[i], lt);
7980
}
8081
else
8182
{
82-
template = JsonToSql.GetSqlBuilder(subtable, 0, 0, where[i].ToString(), zht);
83-
var df = DapperDBHelp.QueryFirstOrDefault(_options.ConnectionString, template.RawSql, template.Parameters);
83+
template = sqlbuilder.GetSqlBuilder(subtable, 0, 0, where[i].ToString(), zht);
84+
var df = db.QueryFirstOrDefault( template.RawSql, template.Parameters);
8485
if (df != null)
8586
{
8687
zht.Add(subtable, JToken.FromObject(df));
@@ -103,8 +104,8 @@ public ActionResult Query([FromBody]string json)
103104
jb.Remove("count");
104105
foreach (var t in jb)
105106
{
106-
var template = JsonToSql.GetSqlBuilder(t.Key, page, count, t.Value.ToString(), null);
107-
foreach (var d in DapperDBHelp.Query(_options.ConnectionString, template.RawSql, template.Parameters))
107+
var template = sqlbuilder.GetSqlBuilder(t.Key, page, count, t.Value.ToString(), null);
108+
foreach (var d in db.Query( template.RawSql, template.Parameters))
108109
{
109110
htt.Add(JToken.FromObject(d));
110111
}
@@ -113,8 +114,8 @@ public ActionResult Query([FromBody]string json)
113114
}
114115
else
115116
{
116-
var template = JsonToSql.GetSqlBuilder(key, 0, 0, item.Value.ToString(), ht);
117-
var df = DapperDBHelp.QueryFirstOrDefault(_options.ConnectionString, template.RawSql, template.Parameters);
117+
var template = sqlbuilder.GetSqlBuilder(key, 0, 0, item.Value.ToString(), ht);
118+
var df = db.QueryFirstOrDefault( template.RawSql, template.Parameters);
118119
if (df != null)
119120
{
120121
ht.Add(key, JToken.FromObject(df));
@@ -161,7 +162,7 @@ public ActionResult Add([FromBody]string json)
161162
}
162163
string sql = sb.ToString().TrimEnd(',') + val.ToString().TrimEnd(',') + ");SELECT CAST(SCOPE_IDENTITY() as int);";
163164

164-
using (var sqlConnection = new SqlConnection(_options.ConnectionString))
165+
using (var sqlConnection = db.Connection)
165166
{
166167
sqlConnection.Open();
167168
int id = sqlConnection.ExecuteScalar<int>(sql, p);
@@ -217,7 +218,7 @@ public ActionResult Edit([FromBody]string json)
217218
p.Add($"@{f.Key}", f.Value.ToString());
218219
}
219220
string sql = sb.ToString().TrimEnd(',') + " where id=@id;";
220-
using (var sqlConnection = new SqlConnection(_options.ConnectionString))
221+
using (var sqlConnection = db.Connection)
221222
{
222223
sqlConnection.Open();
223224
sqlConnection.Execute(sql, p);
@@ -269,7 +270,7 @@ public ActionResult Remove([FromBody]string json)
269270
p.Add($"@{f.Key}", f.Value.ToString());
270271
}
271272
string sql = sb.ToString().TrimEnd(',');
272-
using (var sqlConnection = new SqlConnection(_options.ConnectionString))
273+
using (var sqlConnection = db.Connection)
273274
{
274275
sqlConnection.Open();
275276
sqlConnection.Execute(sql, p);

APIJSON.NET/APIJSON.NET/DapperDBHelp.cs

+30-5
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,46 @@
11
namespace APIJSON.NET
22
{
33
using Dapper;
4+
using Microsoft.Extensions.Options;
5+
using MySql.Data.MySqlClient;
46
using System.Collections.Generic;
7+
using System.Data;
58
using System.Data.SqlClient;
6-
public static class DapperDBHelp
9+
public class DapperHelper
710
{
8-
public static dynamic QueryFirstOrDefault(string ConnectionString, string sql, object param)
11+
12+
private DapperOptions _options;
13+
14+
public DapperHelper(IOptions<DapperOptions> options)
915
{
10-
using (var sqlConnection = new SqlConnection(ConnectionString))
16+
this._options = options.Value;
17+
}
18+
public IDbConnection Connection
19+
{
20+
get
21+
{
22+
if (!string.IsNullOrEmpty(_options.MySql))
23+
{
24+
return new MySqlConnection(_options.MySql);
25+
}
26+
else
27+
{
28+
return new SqlConnection(_options.SqlServer);
29+
}
30+
}
31+
}
32+
33+
public dynamic QueryFirstOrDefault(string sql, object param)
34+
{
35+
using (var sqlConnection = Connection)
1136
{
1237
sqlConnection.Open();
1338
return sqlConnection.QueryFirstOrDefault(sql, param);
1439
}
1540
}
16-
public static IEnumerable<dynamic> Query(string ConnectionString, string sql, object param)
41+
public IEnumerable<dynamic> Query( string sql, object param)
1742
{
18-
using (var sqlConnection = new SqlConnection(ConnectionString))
43+
using (var sqlConnection = Connection)
1944
{
2045
sqlConnection.Open();
2146
return sqlConnection.Query(sql, param);

APIJSON.NET/APIJSON.NET/DapperOptions.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
{
33
public class DapperOptions
44
{
5-
public string ConnectionString { get; set; }
5+
public string SqlServer { get; set; }
6+
public string MySql { get; set; }
67
}
78
}

APIJSON.NET/APIJSON.NET/JsonToSql.cs

+31-4
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,55 @@
11
namespace APIJSON.NET
22
{
33
using Dapper;
4+
using Microsoft.Extensions.Options;
45
using Newtonsoft.Json.Linq;
56
using System;
7+
using System.Collections.Generic;
68
using System.Linq;
7-
public static class JsonToSql
9+
public class JsonToSql
810
{
9-
public static SqlBuilder.Template GetSqlBuilder(string subtable, int page, int count, string json, JObject dd)
11+
/// <summary>
12+
/// 对应数据表
13+
/// </summary>
14+
static Dictionary<string, string> dict = new Dictionary<string, string>
15+
{
16+
{"user", "apijson_user"},
17+
};
18+
private DapperOptions _options;
19+
20+
public JsonToSql(IOptions<DapperOptions> options)
21+
{
22+
this._options = options.Value;
23+
}
24+
public SqlBuilder.Template GetSqlBuilder(string subtable, int page, int count, string json, JObject dd)
1025
{
1126
if (!subtable.IsTable())
1227
{
1328
throw new Exception($"表名{subtable}不正确!");
1429
}
30+
if (dict.ContainsKey(subtable.ToLower()))
31+
{
32+
subtable = dict.GetValueOrDefault(subtable.ToLower());
33+
}
1534
JObject values = JObject.Parse(json);
1635
page = values["page"] == null ? page : int.Parse(values["page"].ToString());
1736
count = values["count"] == null ? count : int.Parse(values["count"].ToString());
1837
values.Remove("page");
1938
values.Remove("count");
2039
var builder = new SqlBuilder();
21-
string pagesql = $"select /**select**/ from [{subtable}] /**where**/ /**groupby**/ /**having**/";
40+
string pagesql = $"select /**select**/ from {subtable} /**where**/ /**groupby**/ /**having**/";
2241
if (count > 0)
2342
{
24-
pagesql = $@"select * from (select row_number()over(order by id)rownumber,/**select**/ from [{subtable}] /**where**/ /**groupby**/ /**having**/) a
43+
if (!string.IsNullOrEmpty(_options.MySql))
44+
{
45+
pagesql = $@"select /**select**/ from {subtable} /**where**/ /**groupby**/ /**having**/ limit {(page * count) + 1},{(page * count) + count}";
46+
}
47+
else
48+
{
49+
pagesql = $@"select * from (select row_number()over(order by id)rownumber,/**select**/ from {subtable} /**where**/ /**groupby**/ /**having**/) a
2550
where rownumber between {(page * count) + 1} and {(page * count) + count}";
51+
}
52+
2653
}
2754
var template = builder.AddTemplate(pagesql);
2855
//查询字段

APIJSON.NET/APIJSON.NET/Startup.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,17 @@ public void ConfigureServices(IServiceCollection services)
2727

2828
services.Configure<DapperOptions>(options =>
2929
{
30-
options.ConnectionString = Configuration.GetConnectionString("Default");
30+
options.MySql = Configuration.GetConnectionString("MySql");
31+
options.SqlServer = Configuration.GetConnectionString("SqlServer");
3132
});
3233

3334
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
3435
services.AddSwaggerGen(c =>
3536
{
3637
c.SwaggerDoc("v1", new Info { Title = "APIJSON.NET", Version = "v1" });
3738
});
39+
services.AddSingleton<DapperHelper>();
40+
services.AddSingleton<JsonToSql>();
3841
}
3942

4043
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -46,6 +49,7 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
4649
}
4750

4851
app.UseMvc();
52+
4953
app.UseSwagger();
5054
app.UseSwaggerUI(c =>
5155
{

APIJSON.NET/APIJSON.NET/appsettings.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"ConnectionStrings": {
3-
"Default": "Server=liaozengbo\\sql2018; Database=Sample;User Id=sa;Password=sa123;"
3+
"SqlServer": "Server=liaozengbo\\sql2018; Database=Sample;User Id=sa;Password=sa123;",
4+
"MySql": "Server=localhost; Database=test; User Id=root;Password=password;charset=UTF8;"
45
},
56
"Logging": {
67
"LogLevel": {

0 commit comments

Comments
 (0)