Controllers控制曾中sqllite连接代码
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace SQLiteHelper
{
///
/// SQLiteHelper is a utility class similar to "SQLHelper" in MS
/// Data Access Application Block and follows similar pattern.
///
public class SQLiteHelper
{
///
/// Creates a new instance. The ctor is marked private since all members are static.
///
private SQLiteHelper()
{
}
public static string Conn { get; set; }
//private static string Conn = System.Configuration.ConfigurationManager.ConnectionStrings["sqlite"].ConnectionString;
public static DataTable ExecuteDataTable(string sqlCom)
{
DataTable dt = new DataTable();
DataSet ds = ExecuteDataSet(Conn, sqlCom, null);
if (ds.Tables != null && ds.Tables.Count > 0)
{
dt = ds.Tables[0];
}
return dt;
}
public static int ExecuteNonQuery(string sqlCom)
{
return ExecuteNonQuery(Conn, sqlCom, null);
}
public static string MdfFilePath = "";
public static string MdfFileName = "";
public static string MdfEmpPicPath = "";
///
/// Creates the command.
///
/// Connection.
/// Command text.
/// Command parameters.
/// SQLite Command
public static SQLiteCommand CreateCommand(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
{
SQLiteCommand cmd = new SQLiteCommand(commandText, connection);
if (commandParameters.Length > 0)
{
foreach (SQLiteParameter parm in commandParameters)
cmd.Parameters.Add(parm);
}
return cmd;
}
///
/// DataTable批量加入SQLite数据库
///
///
///
public static string InsertByDataTable(DataTable dataTable)
{
string result = string.Empty;
if (null == dataTable || dataTable.Rows.Count <= 0)
{
return "添加失败!DataTable暂无数据!";
}
if (string.IsNullOrEmpty(dataTable.TableName))
{
return "添加失败!请先设置DataTable的名称!";
}
// 构建INSERT语句
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO " + dataTable.TableName + "(");
for (int i = 0; i < dataTable.Columns.Count; i++)
{
sb.Append(dataTable.Columns[i].ColumnName + ",");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append(") VALUES ");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
sb.Append("(");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
sb.Append("'" + dataTable.Rows[i][j] + "',");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append("),");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.Append(";");
int res = -1;
using (SQLiteConnection con = new SQLiteConnection(Conn))
{
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand(sb.ToString(), con))
{
try
{
res = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
res = -1;
// Unknown column 'names' in 'field list'
result = "操作失败!" + ex.Message.Replace("Unknown column", "未知列").Replace("in 'field list'", "存在字段集合中!");
}
}
}
if (res > 0)
{
result = "success";
}
return result;
}
///
/// Creates the command.
///
/// Connection string.
/// Command text.
/// Command parameters.
/// SQLite Command
public static SQLiteCommand CreateCommand(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
{
SQLiteConnection cn = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand(commandText, cn);
if (commandParameters.Length > 0)
{
foreach (SQLiteParameter parm in commandParameters)
cmd.Parameters.Add(parm);
}
return cmd;
}
///
/// Creates the parameter.
///
/// Name of the parameter.
/// Parameter type.
/// Parameter value.
/// SQLiteParameter
public static SQLiteParameter CreateParameter(string parameterName, System.Data.DbType parameterType, object parameterValue)
{
SQLiteParameter parameter = new SQLiteParameter();
parameter.DbType = parameterType;
parameter.ParameterName = parameterName;
parameter.Value = parameterValue;
return parameter;
}
///
/// Shortcut method to execute dataset from SQL Statement and object[] arrray of parameter values
///
/// SQLite Connection string
/// SQL Statement with embedded "@param" style parameter names
/// object[] array of parameter values
///
public static DataSet ExecuteDataSet(string connectionString, string commandText, object[] paramList)
{
SQLiteConnection cn = new SQLiteConnection(connectionString);
SQLiteCommand cmd = cn.CreateCommand();
cmd.CommandText = commandText;
if (paramList != null)
{
AttachParameters(cmd, commandText, paramList);
}
DataSet ds = new DataSet();
if (cn.State == ConnectionState.Closed)
cn.Open();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(ds);
da.Dispose();
cmd.Dispose();
cn.Close();
return ds;
}
///
/// Shortcut method to execute dataset from SQL Statement and object[] arrray of parameter values
///
/// Connection.
/// Command text.
/// Param list.
///
public static DataSet ExecuteDataSet(SQLiteConnection cn, string commandText, object[] paramList)
{
SQLiteCommand cmd = cn.CreateCommand();
cmd.CommandText = commandText;
if (paramList != null)
{
AttachParameters(cmd, commandText, paramList);
}
DataSet ds = new DataSet();
if (cn.State == ConnectionState.Closed)
cn.Open();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(ds);
da.Dispose();
cmd.Dispose();
cn.Close();
return ds;
}
///
/// Executes the dataset from a populated Command object.
///
/// Fully populated SQLiteCommand
/// DataSet
public static DataSet ExecuteDataset(SQLiteCommand cmd)
{
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
DataSet ds = new DataSet();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(ds);
da.Dispose();
cmd.Connection.Close();
cmd.Dispose();
return ds;
}
///
/// Executes the dataset in a SQLite Transaction
///
/// SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call.
/// Command text.
/// Sqlite Command parameters.
/// DataSet
/// user must examine Transaction Object and handle transaction.connection .Close, etc.
public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed, please provide an open transaction.", "transaction");
IDbCommand cmd = transaction.Connection.CreateCommand();
cmd.CommandText = commandText;
foreach (SQLiteParameter parm in commandParameters)
{
cmd.Parameters.Add(parm);
}
if (transaction.Connection.State == ConnectionState.Closed)
transaction.Connection.Open();
DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
return ds;
}
///
/// Executes the dataset with Transaction and object array of parameter values.
///
/// SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call.
/// Command text.
/// object[] array of parameter values.
/// DataSet
/// user must examine Transaction Object and handle transaction.connection .Close, etc.
public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, object[] commandParameters)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed, please provide an open transaction.", "transaction");
IDbCommand cmd = transaction.Connection.CreateCommand();
cmd.CommandText = commandText;
AttachParameters((SQLiteCommand)cmd, cmd.CommandText, commandParameters);
if (transaction.Connection.State == ConnectionState.Closed)
transaction.Connection.Open();
DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
return ds;
}
#region UpdateDataset
///
/// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
///
///
/// e.g.:
/// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
///
/// A valid SQL statement to insert new records into the data source
/// A valid SQL statement to delete records from the data source
/// A valid SQL statement used to update records in the data source
/// The DataSet used to update the data source
/// The DataTable used to update the data source.
public static void UpdateDataset(SQLiteCommand insertCommand, SQLiteCommand deleteCommand, SQLiteCommand updateCommand, DataSet dataSet, string tableName)
{
if (insertCommand == null) throw new ArgumentNullException("insertCommand");
if (deleteCommand == null) throw new ArgumentNullException("deleteCommand");
if (updateCommand == null) throw new ArgumentNullException("updateCommand");
if (tableName == null || tableName.Length == 0) throw new ArgumentNullException("tableName");
// Create a SQLiteDataAdapter, and dispose of it after we are done
using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter())
{
// Set the data adapter commands
dataAdapter.UpdateCommand = updateCommand;
dataAdapter.InsertCommand = insertCommand;
dataAdapter.DeleteCommand = deleteCommand;
// Update the dataset changes in the data source
dataAdapter.Update(dataSet, tableName);
// Commit all the changes made to the DataSet
dataSet.AcceptChanges();
}
}
#endregion
///
/// ShortCut method to return IDataReader
/// NOTE: You should explicitly close the Command.connection you passed in as
/// well as call Dispose on the Command after reader is closed.
/// We do this because IDataReader has no underlying Connection Property.
///
/// SQLiteCommand Object
/// SQL Statement with optional embedded "@param" style parameters
/// object[] array of parameter values
/// IDataReader
public static IDataReader ExecuteReader(SQLiteCommand cmd, string commandText, object[] paramList)
{
if (cmd.Connection == null)
throw new ArgumentException("Command must have live connection attached.", "cmd");
cmd.CommandText = commandText;
AttachParameters(cmd, commandText, paramList);
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
IDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return rdr;
}
///
/// Shortcut to ExecuteNonQuery with SqlStatement and object[] param values
///
/// SQLite Connection String
/// Sql Statement with embedded "@param" style parameters
/// object[] array of parameter values
///
public static int ExecuteNonQuery(string connectionString, string commandText, params object[] paramList)
{
SQLiteConnection cn = new SQLiteConnection(connectionString);
SQLiteCommand cmd = cn.CreateCommand();
cmd.CommandText = commandText;
AttachParameters(cmd, commandText, paramList);
if (cn.State == ConnectionState.Closed)
cn.Open();
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
return result;
}
public static int ExecuteNonQuery(SQLiteConnection cn, string commandText, params object[] paramList)
{
SQLiteCommand cmd = cn.CreateCommand();
cmd.CommandText = commandText;
AttachParameters(cmd, commandText, paramList);
if (cn.State == ConnectionState.Closed)
cn.Open();
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
cn.Close();
return result;
}
///
/// Executes non-query sql Statment with Transaction
///
/// SQLiteTransaction. Transaction consists of Connection, Transaction, /// and Command, all of which must be created prior to making this method call.
/// Command text.
/// Param list.
/// Integer
/// user must examine Transaction Object and handle transaction.connection .Close, etc.
public static int ExecuteNonQuery(SQLiteTransaction transaction, string commandText, params object[] paramList)
{
if (transaction == null) throw new ArgumentNullException("transaction");
if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed, please provide an open transaction.", "transaction");
IDbCommand cmd = transaction.Connection.CreateCommand();
cmd.CommandText = commandText;
AttachParameters((SQLiteCommand)cmd, cmd.CommandText, paramList);
if (transaction.Connection.State == ConnectionState.Closed)
transaction.Connection.Open();
int result = cmd.ExecuteNonQuery();
cmd.Dispose();
return result;
}
///
/// Executes the non query.
///
/// CMD.
///
public static int ExecuteNonQuery(IDbCommand cmd)
{
if (cmd.Connection.State == ConnectionState.Closed)
cmd.Connection.Open();
int result = cmd.ExecuteNonQuery();
cmd.Connection.Close();
cmd.Dispose();
return result;
}
///
/// Shortcut to ExecuteScalar with Sql Statement embedded params and object[] param values
///
/// SQLite Connection String
/// SQL statment with embedded "@param" style parameters
/// object[] array of param values
///
public static object ExecuteScalar(string connectionString, string commandText, params object[] paramList)
{
SQLiteConnection cn = new SQLiteConnection(connectionString);
SQLiteCommand cmd = cn.CreateCommand();
cmd.CommandText = commandText;
AttachParameters(cmd, commandText, paramList);
if (cn.State == ConnectionState.Closed)
cn.Open();
object result = cmd.ExecuteScalar();
cmd.Dispose();
cn.Close();
return result;
}
///
/// Execute XmlReader with complete Command
///
/// SQLite Command
/// XmlReader
public static XmlReader ExecuteXmlReader(IDbCommand command)
{ // open the connection if necessary, but make sure we
// know to close it when we�re done.
if (command.Connection.State != ConnectionState.Open)
{
command.Connection.Open();
}
// get a data adapter
SQLiteDataAdapter da = new SQLiteDataAdapter((SQLiteCommand)command);
DataSet ds = new DataSet();
// fill the data set, and return the schema information
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
// convert our dataset to XML
StringReader stream = new StringReader(ds.GetXml());
command.Connection.Close();
// convert our stream of text to an XmlReader
return new XmlTextReader(stream);
}
///
/// Parses parameter names from SQL Statement, assigns values from object array , /// and returns fully populated ParameterCollection.
///
/// Sql Statement with "@param" style embedded parameters
/// object[] array of parameter values
/// SQLiteParameterCollection
/// Status experimental. Regex appears to be handling most issues. Note that parameter object array must be in same ///order as parameter names appear in SQL statement.
private static SQLiteParameterCollection AttachParameters(SQLiteCommand cmd, string commandText, params object[] paramList)
{
if (paramList == null || paramList.Length == 0) return null;
SQLiteParameterCollection coll = cmd.Parameters;
string parmString = commandText.Substring(commandText.IndexOf("@"));
// pre-process the string so always at least 1 space after a comma.
parmString = parmString.Replace(",", " ,");
// get the named parameters into a match collection
string pattern = @"(@)\S*(.*?)\b";
Regex ex = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection mc = ex.Matches(parmString);
string[] paramNames = new string[mc.Count];
int i = 0;
foreach (Match m in mc)
{
paramNames[i] = m.Value;
i++;
}
// now let's type the parameters
int j = 0;
Type t = null;
foreach (object o in paramList)
{
t = o.GetType();
SQLiteParameter parm = new SQLiteParameter();
switch (t.ToString())
{
case ("DBNull"):
case ("Char"):
case ("SByte"):
case ("UInt16"):
case ("UInt32"):
case ("UInt64"):
throw new SystemException("Invalid data type");
case ("System.String"):
parm.DbType = DbType.String;
parm.ParameterName = paramNames[j];
parm.Value = (string)paramList[j];
coll.Add(parm);
break;
case ("System.Byte[]"):
parm.DbType = DbType.Binary;
parm.ParameterName = paramNames[j];
parm.Value = (byte[])paramList[j];
coll.Add(parm);
break;
case ("System.Int32"):
parm.DbType = DbType.Int32;
parm.ParameterName = paramNames[j];
parm.Value = (int)paramList[j];
coll.Add(parm);
break;
case ("System.Boolean"):
parm.DbType = DbType.Boolean;
parm.ParameterName = paramNames[j];
parm.Value = (bool)paramList[j];
coll.Add(parm);
break;
case ("System.DateTime"):
parm.DbType = DbType.DateTime;
parm.ParameterName = paramNames[j];
parm.Value = Convert.ToDateTime(paramList[j]);
coll.Add(parm);
break;
case ("System.Double"):
parm.DbType = DbType.Double;
parm.ParameterName = paramNames[j];
parm.Value = Convert.ToDouble(paramList[j]);
coll.Add(parm);
break;
case ("System.Decimal"):
parm.DbType = DbType.Decimal;
parm.ParameterName = paramNames[j];
parm.Value = Convert.ToDecimal(paramList[j]);
break;
case ("System.Guid"):
parm.DbType = DbType.Guid;
parm.ParameterName = paramNames[j];
parm.Value = (System.Guid)(paramList[j]);
break;
case ("System.Object"):
parm.DbType = DbType.Object;
parm.ParameterName = paramNames[j];
parm.Value = paramList[j];
coll.Add(parm);
break;
default:
throw new SystemException("Value is of unknown data type");
} // end switch
j++;
}
return coll;
}
///
/// Executes non query typed params from a DataRow
///
/// Command.
/// Data row.
/// Integer result code
public static int ExecuteNonQueryTypedParams(IDbCommand command, DataRow dataRow)
{
int retVal = 0;
// If the row has values, the store procedure parameters must be initialized
if (dataRow != null && dataRow.ItemArray.Length > 0)
{
// Set the parameters values
AssignParameterValues(command.Parameters, dataRow);
retVal = ExecuteNonQuery(command);
}
else
{
retVal = ExecuteNonQuery(command);
}
return retVal;
}
///
/// This method assigns dataRow column values to an IDataParameterCollection
///
/// The IDataParameterCollection to be assigned values
/// The dataRow used to hold the command's parameter values
/// Thrown if any of the parameter names are invalid.
protected internal static void AssignParameterValues(IDataParameterCollection commandParameters, DataRow dataRow)
{
if (commandParameters == null || dataRow == null)
{
// Do nothing if we get no data
return;
}
DataColumnCollection columns = dataRow.Table.Columns;
int i = 0;
// Set the parameters values
foreach (IDataParameter commandParameter in commandParameters)
{
// Check the parameter name
if (commandParameter.ParameterName == null ||
commandParameter.ParameterName.Length <= 1)
throw new InvalidOperationException(string.Format(
"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
i, commandParameter.ParameterName));
if (columns.Contains(commandParameter.ParameterName))
commandParameter.Value = dataRow[commandParameter.ParameterName];
else if (columns.Contains(commandParameter.ParameterName.Substring(1)))
commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
i++;
}
}
///
/// This method assigns dataRow column values to an array of IDataParameters
///
/// Array of IDataParameters to be assigned values
/// The dataRow used to hold the stored procedure's parameter values
/// Thrown if any of the parameter names are invalid.
protected void AssignParameterValues(IDataParameter[] commandParameters, DataRow dataRow)
{
if ((commandParameters == null) || (dataRow == null))
{
// Do nothing if we get no data
return;
}
DataColumnCollection columns = dataRow.Table.Columns;
int i = 0;
// Set the parameters values
foreach (IDataParameter commandParameter in commandParameters)
{
// Check the parameter name
if (commandParameter.ParameterName == null ||
commandParameter.ParameterName.Length <= 1)
throw new InvalidOperationException(string.Format(
"Please provide a valid parameter name on the parameter #{0}, the ParameterName property has the following value: '{1}'.",
i, commandParameter.ParameterName));
if (columns.Contains(commandParameter.ParameterName))
commandParameter.Value = dataRow[commandParameter.ParameterName];
else if (columns.Contains(commandParameter.ParameterName.Substring(1)))
commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)];
i++;
}
}
///
/// This method assigns an array of values to an array of IDataParameters
///
/// Array of IDataParameters to be assigned values
/// Array of objects holding the values to be assigned
/// Thrown if an incorrect number of parameters are passed.
protected void AssignParameterValues(IDataParameter[] commandParameters, params object[] parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
// Do nothing if we get no data
return;
}
// We must have the same number of values as we pave parameters to put them in
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
// Iterate through the IDataParameters, assigning the values from the corresponding position in the
// value array
for (int i = 0, j = commandParameters.Length, k = 0; i < j; i++)
{
if (commandParameters[i].Direction != ParameterDirection.ReturnValue)
{
// If the current array value derives from IDataParameter, then assign its Value property
if (parameterValues[k] is IDataParameter)
{
IDataParameter paramInstance;
paramInstance = (IDataParameter)parameterValues[k];
if (paramInstance.Direction == ParameterDirection.ReturnValue)
{
paramInstance = (IDataParameter)parameterValues[++k];
}
if (paramInstance.Value == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = paramInstance.Value;
}
}
else if (parameterValues[k] == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = parameterValues[k];
}
k++;
}
}
}
}
}
此为view层controllers控制页面在下面view层会对应用到
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using Model;
using MySqlController;
namespace ViewController
{
public class ctlQADataBaseController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlQADataBaseController));
public DataTable QuestionInfo()
{
DataTable dtResult = null;
try
{
string sql = @"SELECT * From tb_question_answer order by Id";
dtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QuestionInfo()]:" + ex.Message + ex.StackTrace);
}
return dtResult;
}
public DataTable QuestionExport()
{
DataTable dtResult = null;
try
{
string sql = @"SELECT Qtype,question,answer,remark From tb_question_answer order by Id";
dtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QuestionExport()]:" + ex.Message + ex.StackTrace);
}
return dtResult;
}
public string Delete(string empIds)
{
string strResult = "fail";
try
{
string sql = $@"delete from tb_UserCardInfo
where emplid in ({empIds})";
int r = SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql);
if (r >= 0)
{
strResult = "success";
}
}
catch (Exception ex)
{
logger.Error("[Delete(string empId)]:" + ex.Message + ex.StackTrace);
}
return strResult;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using Model;
namespace ViewController
{
public class ctlHRActionJudgeController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlQASelectController));
private Random ra = new Random();//随机数
public tb_question_answer QuestionInfo()
{
List lstResult = new List();
tb_question_answer ResultRandom1 = new tb_question_answer();
try
{
string sql = @"SELECT * From tb_question_answer where Qtype in ('SELECT1','JUDGE') order by Id ";
// string sql = string.Format(@"select * from tb_question_answer where Qtype in ('JUDGE','SELECT1');");
//string sql = @"SELECT * From tb_question_answer where Qtype ='SELECT1'";
DataTable dtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
lstResult = DBHelper.ModelConvert.DataTableToList(dtResult).ToList();
int random1 = ra.Next(0, lstResult.Count - 1);
ResultRandom1 = lstResult[random1];
}
catch (Exception ex)
{
logger.Error("[QuestionInfo()]:" + ex.Message + ex.StackTrace);
}
return ResultRandom1;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using Model;
namespace ViewController
{
public class ctlLotteryController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlLotteryController));
public Dictionary QueryUserCardInfo(out DataTable dtCardInfo)
{
Dictionary DicInfo = new Dictionary();
dtCardInfo = new DataTable();
try
{
string sql = $"select distinct t.[EMPLID],t.NAME,t.DESCRSHORT,T.DESCR,t.TSMC_EMP_FLAG from tb_usercardinfo t";
dtCardInfo = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (dtCardInfo != null && dtCardInfo.Rows.Count > 0)
{
for (int i = 0; i < dtCardInfo.Rows.Count; i++)
{
tb_UserCardInfo info = new tb_UserCardInfo();
info.EMPLID = dtCardInfo.Rows[i]["EMPLID"].ToString();
info.NAME = dtCardInfo.Rows[i]["NAME"].ToString();
info.DESCRSHORT = dtCardInfo.Rows[i]["DESCRSHORT"].ToString();
info.DESCR = dtCardInfo.Rows[i]["DESCR"].ToString();
info.TSMC_EMP_FLAG = dtCardInfo.Rows[i]["TSMC_EMP_FLAG"].ToString();
DicInfo.Add(info.EMPLID, info);
}
}
}
catch (Exception ex)
{
logger.Error("[QueryUserCardInfoByCard_NUM()] " + ex.Message + ex.StackTrace);
}
return DicInfo;
}
public List QueryDeptList()
{
List lstDept = new List();
try
{
string sql = $"select distinct t.DESCRSHORT from tb_usercardinfo t";
DataTable dt = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
lstDept.Add(dt.Rows[i]["DESCRSHORT"].ToString());
}
}
}
catch (Exception ex)
{
logger.Error("[QueryDeptList()] " + ex.Message + ex.StackTrace);
}
return lstDept;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using Model;
using MySqlController;
namespace ViewController
{
public class ctlCardInfoLoadController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlCardInfoLoadController));
public DataTable CardInfoQuery()
{
DataTable dtResult = null;
try
{
string sql = @"SELECT * From tb_UserCardInfo order by DESCRSHORT,DESCR,EMPLID";
dtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[CardInfoQuery()]:" + ex.Message + ex.StackTrace);
}
return dtResult;
}
public List MonthListQuery()
{
List lstResult = null;
try
{
string sql = @"select distinct(tb_performance_total.MONTH) MON from tb_performance_total order by tb_performance_total.MONTH desc";
DataTable dtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (dtResult != null && dtResult.Rows.Count > 0)
{
lstResult = new List();
for (int i = 0; i < dtResult.Rows.Count; i++)
{
lstResult.Add(dtResult.Rows[i]["MON"].ToString());
}
}
}
catch (Exception ex)
{
logger.Error("[MonthListQuery()]:" + ex.Message + ex.StackTrace);
}
return lstResult;
}
public string Update(tb_UserCardInfo cardInfo)
{
string strResult = "fail";
try
{
string sql = $@"update tb_UserCardInfo set CARD_NUM='{cardInfo.CARD_NUM}',
NAME='{cardInfo.NAME}',
DESCRSHORT='{cardInfo.DESCRSHORT}',
DESCR='{cardInfo.DESCR}',
TSMC_EMP_FLAG='{cardInfo.TSMC_EMP_FLAG}'
where emplid='{cardInfo.EMPLID}'";
int r = SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql);
if(r>=0)
{
strResult = "success";
}
}
catch (Exception ex)
{
logger.Error("[Update(tb_UserCardInfo cardInfo)]:" + ex.Message + ex.StackTrace);
}
return strResult;
}
public string Delete(string empIds)
{
string strResult = "fail";
try
{
string sql = $@"delete from tb_UserCardInfo
where emplid in ({empIds})";
int r = SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql);
if (r >= 0)
{
strResult = "success";
}
}
catch (Exception ex)
{
logger.Error("[Delete(string empId)]:" + ex.Message + ex.StackTrace);
}
return strResult;
}
}
}
using log4net;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace ViewController
{
public class ctlQAlogController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlQAlogController));
public int QueryQALog(string empId)
{
//验证是否已经答题过
int result = 0;
try
{
string sql = $@"select* from tb_qalog where empid = '{empId}'";
DataTable DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (DtResult != null)
{
result = DtResult.Rows.Count;
}
}
catch (Exception ex)
{
logger.Error("[QueryQALog(string empId))] " + ex.Message + ex.StackTrace);
}
return result;
}
public int QueryREMARK(string remark)
{
//验证是否是Admin Remark类中存在的CardNum
int result = 0;
try
{
string sql = $@"select * from tb_admininfo where remark='{remark}' ";
DataTable DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (DtResult != null)
{
result = DtResult.Rows.Count;
}
}
catch (Exception ex)
{
logger.Error("[QueryREMARK(string REMARK)]" + ex.Message + ex.StackTrace);
}
return result;
}
public DataTable QueryQALogRecord()
{
DataTable dtus = null;
try
{
string sql = $"select * from tb_qalog ";//where empid='{empId}'
dtus = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[ QueryQALogRecord()]"+ex.Message+ex.StackTrace);
}
return dtus;
}
public DataTable QueryQALogRecordEmpId(string empId)
{
DataTable dt = null;
try
{
string sql = $"select * from tb_qalog where empid='{empId}'";
dt = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex )
{
logger.Error("[ QueryQALogRecord(string empId)]" + ex.Message + ex.StackTrace);//
}
return dt;
}
public DataTable QueryALogDelete()
{
DataTable dt = null;
try
{
string sql = $"delete from tb_qalog";
dt = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QueryALogDelete()]"+ex.Message+ex.StackTrace);
}
return dt;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using Model;
namespace ViewController
{
public class ctlQASelectController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlQASelectController));
private Random ra = new Random();//随机数
public List QuestionInfo()
{
List lstResult = new List();
List lstResultRandom10 = new List();
try
{
string sql = @"SELECT * From tb_question_answer where Qtype='SELECT' order by Id ";
DataTable dtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
lstResult = DBHelper.ModelConvert.DataTableToList(dtResult).ToList();
int[] intArr = GetRandomArray(10, 0, lstResult.Count-1);
foreach (int item in intArr)
{
lstResultRandom10.Add(lstResult[item]);
}
}
catch (Exception ex)
{
logger.Error("[QuestionInfo()]:" + ex.Message + ex.StackTrace);
}
return lstResultRandom10;
}
// Number随机数个数
// minNum随机数下限
// maxNum随机数上限
public int[] GetRandomArray(int Number, int minNum, int maxNum)
{
int j;
int[] b = new int[Number];
Random r = new Random();
for (j = 0; j < Number; j++)
{
int i = r.Next(minNum, maxNum + 1);
int num = 0;
for (int k = 0; k < j; k++)
{
if (b[k] == i)
{
num = num + 1;
}
}
if (num == 0)
{
b[j] = i;
}
else
{
j = j - 1;
}
}
return b;
}
//private void frmParent_Load(object sender, EventArgs e)
//{
// ctlQASelect child = new ctlQASelect();
// child.RefreshEvent += this.NeedRefresh;//注册事件
// child.Show();
//}
//private void NeedRefresh(object sender, EventArgs e)
//{
// MessageBox.Show("需要刷新!");
// //在这里写刷新逻辑
//}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using Model;
namespace ViewController
{
public class ctlSignController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(ctlSignController));
public tb_UserCardInfo QueryUserCardInfoByCard_NUM(string cardNum)
{
tb_UserCardInfo info = new tb_UserCardInfo();
try
{
string sql = $"select * from tb_usercardinfo where card_num='{cardNum}'";
DataTable dt = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (dt!=null && dt.Rows.Count>0)
{
info.CARD_NUM = dt.Rows[0]["CARD_NUM"].ToString();
info.EMPLID = dt.Rows[0]["EMPLID"].ToString();
info.NAME = dt.Rows[0]["NAME"].ToString();
info.DESCRSHORT = dt.Rows[0]["DESCRSHORT"].ToString();
info.DESCR = dt.Rows[0]["DESCR"].ToString();
info.TSMC_EMP_FLAG= dt.Rows[0]["TSMC_EMP_FLAG"].ToString();
}
}
catch (Exception ex)
{
logger.Error("[QueryUserCardInfoByCard_NUM(string cardNum)] " + ex.Message + ex.StackTrace);
}
return info;
}
public tb_UserCardInfo QueryUserCardInfoByEmpId(string empId)
{
tb_UserCardInfo info = new tb_UserCardInfo();
try
{
string sql = $"select * from tb_usercardinfo where Emplid='{empId}'";//vs2015版本及以上才会有的 判断输入的ID是否和数据库中的ID相等
DataTable dt = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
info.CARD_NUM = dt.Rows[0]["CARD_NUM"].ToString();
info.EMPLID = dt.Rows[0]["EMPLID"].ToString();
info.NAME = dt.Rows[0]["NAME"].ToString();
info.DESCRSHORT = dt.Rows[0]["DESCRSHORT"].ToString();
info.DESCR = dt.Rows[0]["DESCR"].ToString();
info.TSMC_EMP_FLAG = dt.Rows[0]["TSMC_EMP_FLAG"].ToString();
}
}
catch (Exception ex)
{
logger.Error("[QueryUserCardInfoByCard_NUM(string cardNum)] " + ex.Message + ex.StackTrace);
}
return info;
}
public Dictionary QueryUserCardInfo()
{
Dictionary DicInfo = new Dictionary();
try
{
string sql = $"select distinct t.* from tb_usercardinfo t";
DataTable dt = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
tb_UserCardInfo info = new tb_UserCardInfo();
info.CARD_NUM = dt.Rows[i]["CARD_NUM"].ToString();
info.EMPLID = dt.Rows[i]["EMPLID"].ToString();
info.NAME = dt.Rows[i]["NAME"].ToString();
info.DESCRSHORT = dt.Rows[i]["DESCRSHORT"].ToString();
info.DESCR = dt.Rows[i]["DESCR"].ToString();
info.TSMC_EMP_FLAG = dt.Rows[i]["TSMC_EMP_FLAG"].ToString();
DicInfo.Add(info.CARD_NUM, info);
}
}
}
catch (Exception ex)
{
logger.Error("[QueryUserCardInfoByCard_NUM(string cardNum)] " + ex.Message + ex.StackTrace);
}
return DicInfo;
}
public string DeleteUserCardInfo(string action_code,string emplID,string signTime)
{
string result = "fail";
try
{
string sql = $@"delete from tb_signlog where action_code='{action_code}' and EMPLID='{emplID}' and STRFTIME('%Y-%m-%d %H:%M:%S', signtime, 'localtime')='{signTime}'";
int r = SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql);
if (r > 0)
{
result = "success";
}
}
catch (Exception ex)
{
logger.Error("[DeleteUserCardInfo()] " + ex.Message + ex.StackTrace);
}
return result;
}
public string InsertSignLog(string action_code,tb_UserCardInfo info)
{
string result = "fail";
try
{
string sql = $@"insert into tb_signlog (action_code,card_num,emplid,name,descrshort,descr,signtime)
values ('{action_code}','{info.CARD_NUM}','{info.EMPLID}','{info.NAME}','{info.DESCRSHORT}','{info.DESCR}',datetime('now'))";
int r = SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql);
if (r>0)
{
result = "success";
}
}
catch (Exception ex)
{
logger.Error("[InsertSignLog(string action_code,tb_UserCardInfo info)] " + ex.Message + ex.StackTrace);
}
return result;
}
public DataTable QuerySignLog(string action_code,out List lstEMP)
{
DataTable DtResult = null;
lstEMP = new List();
try
{
string sql = $@"select EMPLID,NAME,DESCRSHORT,DESCR,STRFTIME('%Y-%m-%d %H:%M:%S', SIGNTIME, 'localtime') SIGNTIME from tb_SignLog where ACTION_CODE='{action_code}' order by SignTIME DESC";
DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (DtResult!=null && DtResult.Rows.Count>0)
{
for (int i = 0; i < DtResult.Rows.Count; i++)
{
lstEMP.Add(DtResult.Rows[i]["EMPLID"].ToString());
}
}
}
catch (Exception ex)
{
logger.Error("[QuerySignLog(string action_code)] " + ex.Message + ex.StackTrace);
}
return DtResult;
}
public DataTable QuerySignLog(string action_code="")
{
DataTable DtResult = null;
try
{
string sql = string.Empty;
if (!string.IsNullOrWhiteSpace(action_code))
{
sql = $@"select ACTION_CODE,EMPLID,NAME,DESCRSHORT,DESCR,STRFTIME('%Y-%m-%d %H:%M:%S', SIGNTIME, 'localtime') SIGNTIME from tb_SignLog where ACTION_CODE='{action_code}' order by SignTIME DESC";
}
else
{
sql = $@"select ACTION_CODE,EMPLID,NAME,DESCRSHORT,DESCR,STRFTIME('%Y-%m-%d %H:%M:%S', SIGNTIME, 'localtime') SIGNTIME from tb_SignLog order by SignTIME DESC";
}
DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QuerySignLog(string action_code)] " + ex.Message + ex.StackTrace);
}
return DtResult;
}
public DataTable QueryLogBySectionSummary(string action_code)
{
DataTable DtResult = null;
try
{
string sql = string.Empty;
if (!string.IsNullOrWhiteSpace(action_code))
{
sql = $@" select DESCR,count(distinct(EMPLID)) CNT from tb_signlog where action_code='{action_code}' group by descr";
}
else
{
sql = $@" select DESCR,count(distinct(EMPLID)) CNT from tb_signlog group by descr";
}
DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QueryLogBySectionSummary(string action_code)] " + ex.Message + ex.StackTrace);
}
return DtResult;
}
public DataTable QueryLogByDeptSummary(string action_code)
{
DataTable DtResult = null;
try
{
string sql = string.Empty;
if (!string.IsNullOrWhiteSpace(action_code))
{
sql = $@"select DESCRSHORT, from tb_signlog where action_code='{action_code}' group by DESCRSHORT";
}
else
{
sql = $@"select DESCRSHORT,count(distinct(EMPLID)) CNT from tb_signlog group by DESCRSHORT";
}
DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QueryLogByDeptSummary(string action_code)] " + ex.Message + ex.StackTrace);
}
return DtResult;
}
public List QuerySignAction_Code()
{
List lstActionCode = new List();
lstActionCode.Add("");
try
{
string sql = $@" select distinct(action_code) ACTION_CODE from tb_signlog";
DataTable DtResult = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
if (DtResult!=null && DtResult.Rows.Count>0)
{
for (int i = 0; i < DtResult.Rows.Count; i++)
{
lstActionCode.Add(DtResult.Rows[i]["ACTION_CODE"].ToString());
}
}
}
catch (Exception ex)
{
logger.Error("[QuerySignAction_Code()] " + ex.Message + ex.StackTrace);
}
return lstActionCode;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using log4net;
using MySqlController;
namespace ViewController
{
public class SysUseLogController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(SysUseLogController));
public static int InsertSysLog(string Action)
{
string sql =string.Format(@"insert into tb_syslog (EMPL_ID,EMPL_NAME,EMPL_ACCOUNT,DEPT_ID,DEPT_ABBRV_NAME,UPDATETIME,tb_syslog.ACTION,ROLE)
values('{0}','{1}','{2}','{3}','{4}',curtime(),'{5}','{6}')",
Action);
int result = 0;
try
{
result = MySqlDBHelper.UpdateMySql(sql);
}
catch (Exception ex)
{
logger.Error("[InsertSysLog(string Action)]:" + ex.Message + ex.StackTrace);
}
return result;
}
public DataTable QuerySysLog()
{
DataTable dtResult = null;
try
{
string sql = @"select * from tb_syslog";
dtResult = MySqlDBHelper.QueryDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QuerySysLog()]:" + ex.Message + ex.StackTrace);
}
return dtResult;
}
}
}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DBHelper;
using log4net;
using Model;
using MySqlController;
using SQLiteHelper;
namespace ViewController
{
public class SysUserInfoController
{
private static readonly ILog logger = LogManager.GetLogger(typeof(SysUserInfoController));
public DataTable QuerySystemUsers()
{
DataTable dtUsers = null;
try
{
string sql = @"SELECT NTID,
ROLE_NAME,
ACTION_CODE,
STRFTIME('%Y-%m-%d %H:%M:%S', EXP_DATE, 'localtime') EXP_DATE,
UPDATE_NTID,
STRFTIME('%Y-%m-%d %H:%M:%S', UPDATE_TIME, 'localtime') UPDATE_TIME,
TSMC_EMP_FLAG,
REMARK,
TB_ADMININFO.PASSWORD
FROM TB_ADMININFO";
dtUsers = SQLiteHelper.SQLiteHelper.ExecuteDataTable(sql);
}
catch (Exception ex)
{
logger.Error("[QuerySystemUsers()]: " + ex.Message.ToString());
}
return dtUsers;
}
public string InsertSystemUsers(string NtId,string Pwd,string role,string actionCode,DateTime dtExp,string emFlag,string remark)
{
string result = "fail";
try
{
string sql = $@"insert into tb_admininfo (NTID,PASSWORD,ROLE_NAME,ACTION_CODE,EXP_DATE,UPDATE_NTID,UPDATE_TIME,TSMC_EMP_FLAG,REMARK)
values('{NtId}','{Pwd}','{role}','{actionCode}',datetime('{dtExp.ToString("yyyy-MM-dd HH:mm:ss")}'),'{UserInfo.NTID}',datetime('now'),'{emFlag}','{remark}') ";
if(SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql)>0)
{
result = "success";
}
}
catch (Exception ex)
{
logger.Error("[InsertSystemUsers(string NtId,string Pwd,string role,string actionCode,DateTime dtExp,string remark)]: " + ex.Message.ToString());
}
return result;
}
public string UpdateSystemUsers(string NtId, string Pwd, string role, string actionCode, DateTime dtExp, string emFlag, string remark,string upDate)
{
string result = "fail";
try
{
string sql = $@"update tb_admininfo set ROLE_NAME='{role}',
PASSWORD='{Pwd}', EXP_DATE=datetime('{dtExp.ToString("yyyy-MM-dd HH:mm:ss")}'),ACTION_CODE='{actionCode}',
UPDATE_NTID='{UserInfo.NTID}',
UPDATE_TIME = datetime('now'),
TSMC_EMP_FLAG='{emFlag}',
REMARK='{remark}'
where NTID='{NtId}' and STRFTIME('%Y-%m-%d %H:%M:%S', UPDATE_TIME, 'localtime')='{upDate}'";
if (SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql) > 0)
{
result = "success";
}
}
catch (Exception ex)
{
logger.Error("[UpdateSystemUsers(string role,string Acc)]: " + ex.Message.ToString());
}
return result;
}
public string DeleteSystemUsers(string NtId, string role, string upDate)
{
string result = "fail";
try
{
string sql = $@"delete from tb_admininfo where ROLE_NAME='{role}' and UPDATE_NTID='{UserInfo.NTID}' and NTID='{NtId}'
and STRFTIME('%Y-%m-%d %H:%M:%S', UPDATE_TIME, 'localtime')='{upDate}'";
if (SQLiteHelper.SQLiteHelper.ExecuteNonQuery(sql) > 0)
{
result = "success";
}
}
catch (Exception ex)
{
logger.Error("[DeleteSystemUsers(string Acc)]: " + ex.Message.ToString());
}
return result;
}
}
}
为各个控制曾代码,码农们自己组合吧哈哈哈