Skip to content

Commit

Permalink
增加SQLiteHelper类
Browse files Browse the repository at this point in the history
  • Loading branch information
1764564459 committed Apr 12, 2019
1 parent c04ff89 commit a98340e
Show file tree
Hide file tree
Showing 4 changed files with 280 additions and 2 deletions.
11 changes: 9 additions & 2 deletions App.config
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="Default" connectionString="Database=OAuthServer;Persist Security Info=True;User ID=sa;Password=123456;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Expand All @@ -15,6 +15,7 @@
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<appSettings>
Expand All @@ -34,4 +35,10 @@
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories>
</system.data>
</configuration>
12 changes: 12 additions & 0 deletions EntityFrameWork.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite, Version=1.0.110.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<HintPath>packages\System.Data.SQLite.Core.1.0.110.0\lib\net46\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Data.SQLite.EF6, Version=1.0.110.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<HintPath>packages\System.Data.SQLite.EF6.1.0.110.0\lib\net46\System.Data.SQLite.EF6.dll</HintPath>
</Reference>
<Reference Include="System.Data.SQLite.Linq, Version=1.0.110.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<HintPath>packages\System.Data.SQLite.Linq.1.0.110.0\lib\net46\System.Data.SQLite.Linq.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
Expand All @@ -90,6 +99,7 @@
<Compile Include="Entity\Auth\AppUserRole.cs" />
<Compile Include="Helper\GPS_To_Baidu.cs" />
<Compile Include="Helper\MongoDbHelper.cs" />
<Compile Include="Helper\SQLiteHelper.cs" />
<Compile Include="Migrations\Configuration.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repository\complex\IRepository\IRepository.cs" />
Expand All @@ -116,5 +126,7 @@
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
<Error Condition="!Exists('packages\System.Data.SQLite.Core.1.0.110.0\build\net46\System.Data.SQLite.Core.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\System.Data.SQLite.Core.1.0.110.0\build\net46\System.Data.SQLite.Core.targets'))" />
</Target>
<Import Project="packages\System.Data.SQLite.Core.1.0.110.0\build\net46\System.Data.SQLite.Core.targets" Condition="Exists('packages\System.Data.SQLite.Core.1.0.110.0\build\net46\System.Data.SQLite.Core.targets')" />
</Project>
255 changes: 255 additions & 0 deletions Helper/SQLiteHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,255 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameWork.Server.Helper
{
//需要NutGet System.Data.SQLite
public class SQLiteHelper : IDisposable
{

private static SQLiteConnection _SQLiteConnect { get; set; }
//库文件夹地址
private static string SQLite_Path = $"{Directory.GetCurrentDirectory()}//SQLite_Data";
//库名字
static string SQLite_Name = $"Vehicle_History.sqlite";
//库的准确地址
static string SQLite_File = $"{SQLite_Path}//{SQLite_Name}";
//连接字符串
private static readonly string str = $"Data Source ={SQLite_File}; Version=3"; //ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
/// <summary>
/// 建库
/// </summary>
public SQLiteHelper()
{
_SQLiteConnect = new SQLiteConnection(str);
//文件夹是否存在
if (!Directory.Exists(SQLite_Path))
Directory.CreateDirectory(SQLite_Path);
//判断数据库是否存在
if (!File.Exists(SQLite_File))
SQLiteConnection.CreateFile(SQLite_File);

createTable();
}

/// <summary>
/// 打开SQLite链接
/// </summary>
public static void Open()
{
if (_SQLiteConnect.State == ConnectionState.Closed)
_SQLiteConnect.Open();
}

//在指定数据库中创建一个table
void createTable()
{
Open();

//检查表是否存在
string sql = "select name from sqlite_master where name='GPS_History'";
DataTable data = ExecuteTable(sql);
if (data.Rows.Count > 0)
return;

sql = "create table GPS_History (Id GUID, Last_Time DATETIME,Data NVARCHAR,Is_Update BOOL)";

SQLiteCommand command = new SQLiteCommand(sql, _SQLiteConnect);

command.ExecuteNonQuery();
}
/// <summary>
/// 增删改
/// 20180723
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="param">sql参数</param>
/// <returns>受影响的行数</returns>
public int ExecuteNonQuery(string sql, params SQLiteParameter[] param)
{
Open();
using (SQLiteCommand cmd = new SQLiteCommand(sql, _SQLiteConnect))
{
if (param != null)
{
cmd.Parameters.AddRange(param);
}

string sql2 = cmd.CommandText;
//con.Close();
return cmd.ExecuteNonQuery();
}

}

/// <summary>
/// 查询
/// 20180723
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="param">sql参数</param>
/// <returns>首行首列</returns>
public object ExecuteScalar(string sql, params SQLiteParameter[] param)
{
Open();
using (SQLiteCommand cmd = new SQLiteCommand(sql, _SQLiteConnect))
{
if (param != null)
{
cmd.Parameters.AddRange(param);
}

return cmd.ExecuteScalar();
}
}

/// <summary>
/// 多行查询
/// 20180723
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="param">sql参数</param>
/// <returns>SQLiteDateReader</returns>
public SQLiteDataReader ExecuteReader(string sql, params SQLiteParameter[] param)
{
Open();
using (SQLiteCommand cmd = new SQLiteCommand(sql, _SQLiteConnect))
{
if (param != null)
{
cmd.Parameters.AddRange(param);
}
try
{
return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
_SQLiteConnect.Close();
_SQLiteConnect.Dispose();
throw ex;
}
}

}

/// <summary>
/// 查询多行数据
/// 20180723
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="param">sql参数</param>
/// <returns>一个表</returns>
public DataTable ExecuteTable(string sql, params SQLiteParameter[] param)
{
DataTable dt = new DataTable();
using (SQLiteDataAdapter sda = new SQLiteDataAdapter(sql, str))
{
if (param != null)
{
sda.SelectCommand.Parameters.AddRange(param);
}
sda.Fill(dt);
}
return dt;
}

/// <summary>
/// 查询封装
/// 20180725
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="fields">查询需要的字段名:"id, name, age"</param>
/// <param name="where">查询条件:"id = 1"</param>
/// <param name="orderBy">排序:"id desc"</param>
/// <param name="limit">分页:"0,10"</param>
/// <param name="param">sql参数</param>
/// <returns>受影响行数</returns>
public DataTable QueryTable(string tbName, string fields = "*", string where = "1", string orderBy = "", string limit = "", params SQLiteParameter[] param)
{
//排序
if (orderBy != "")
{
orderBy = "ORDER BY " + orderBy;//Deom: ORDER BY id desc
}

//分页
if (limit != "")
{
limit = "LIMIT " + limit;//Deom: LIMIT 0,10
}

string sql = string.Format("SELECT {0} FROM `{1}` WHERE {2} {3} {4}", fields, tbName, where, orderBy, limit);

//return sql;
return ExecuteTable(sql, param);

}

/// <summary>
/// 数据插入
/// 20180725
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="insertData">需要插入的数据字典</param>
/// <returns>受影响行数</returns>
public int ExecuteInsert(string tbName, Dictionary<String, String> insertData)
{
string point = "";//分隔符号(,)
string keyStr = "";//字段名拼接字符串
string valueStr = "";//值的拼接字符串

List<SQLiteParameter> param = new List<SQLiteParameter>();
foreach (string key in insertData.Keys)
{
keyStr += string.Format("{0} `{1}`", point, key);
valueStr += string.Format("{0} @{1}", point, key);
param.Add(new SQLiteParameter("@" + key, insertData[key]));
point = ",";
}
string sql = string.Format("INSERT INTO `{0}`({1}) VALUES({2})", tbName, keyStr, valueStr);

//return sql;
return ExecuteNonQuery(sql, param.ToArray());

}

/// <summary>
/// 执行Update语句
/// 20180725
/// </summary>
/// <param name="tbName">表名</param>
/// <param name="where">更新条件:id=1</param>
/// <param name="insertData">需要更新的数据</param>
/// <returns>受影响行数</returns>
public int ExecuteUpdate(string tbName, string where, Dictionary<String, String> insertData)
{
string point = "";//分隔符号(,)
string kvStr = "";//键值对拼接字符串(Id=@Id)

List<SQLiteParameter> param = new List<SQLiteParameter>();
foreach (string key in insertData.Keys)
{
kvStr += string.Format("{0} {1}=@{2}", point, key, key);
param.Add(new SQLiteParameter("@" + key, insertData[key]));
point = ",";
}
string sql = string.Format("UPDATE `{0}` SET {1} WHERE {2}", tbName, kvStr, where);

return ExecuteNonQuery(sql, param.ToArray());

}

public void Dispose()
{
if (_SQLiteConnect != null)
_SQLiteConnect.Dispose();
}
}
}
4 changes: 4 additions & 0 deletions packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,9 @@
<package id="MongoDB.Driver" version="2.8.0" targetFramework="net461" />
<package id="MongoDB.Driver.Core" version="2.8.0" targetFramework="net461" />
<package id="System.Buffers" version="4.4.0" targetFramework="net461" />
<package id="System.Data.SQLite" version="1.0.110.0" targetFramework="net461" />
<package id="System.Data.SQLite.Core" version="1.0.110.0" targetFramework="net461" />
<package id="System.Data.SQLite.EF6" version="1.0.110.0" targetFramework="net461" />
<package id="System.Data.SQLite.Linq" version="1.0.110.0" targetFramework="net461" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net461" />
</packages>

0 comments on commit a98340e

Please sign in to comment.