init: 导入项目到 meswork Gitea

This commit is contained in:
XingCheng3
2026-05-29 10:07:05 +08:00
commit ad9a4106fb
3582 changed files with 460312 additions and 0 deletions

View File

@@ -0,0 +1,468 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SQLiteDBUtility
{
/// <summary>
/// 数据访问基础类(基于SQLite)
/// 可以用户可以修改满足自己项目的需要。
/// </summary>
public abstract class DbHelperSQLite
{
//数据库连接字符串(web.config来配置)可以动态更改connectionString支持多数据库.
public static string connectionString = CreateConnectionString();
public DbHelperSQLite()
{
}
private static string CreateConnectionString()
{
//string dbName = ConfigurationManager.AppSettings["SQLiteDB"];
string sqlLitePath = "data source=" + System.Environment.CurrentDirectory+ "\\db\\MW_DataFactory_App.db" + ";version=3;";
return sqlLitePath;
}
#region
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return 1;
}
else
{
return int.Parse(obj.ToString());
}
}
public static bool Exists(string strSql)
{
object obj = GetSingle(strSql);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
public static bool Exists(string strSql, params SQLiteParameter[] cmdParms)
{
object obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
cmdresult = 0;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
#endregion
#region SQL语句
/// <summary>
/// 执行SQL语句返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
connection.Close();
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static void ExecuteSqlTran(ArrayList SQLStringList)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
SQLiteTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n].ToString();
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
cmd.ExecuteNonQuery();
}
}
tx.Commit();
}
catch (System.Data.SQLite.SQLiteException E)
{
tx.Rollback();
throw new Exception(E.Message);
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, string content)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// 执行一条计算查询结果语句返回查询结果object
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果object</returns>
public static object GetSingle(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SQLite.SQLiteException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句返回SQLiteDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public static SQLiteDataReader ExecuteReader(string strSQL)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
try
{
connection.Open();
SQLiteDataReader myReader = cmd.ExecuteReader();
return myReader;
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SQLite.SQLiteException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region SQL语句
/// <summary>
/// 执行SQL语句返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SQLite.SQLiteException E)
{
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 执行多条SQL语句实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表key为sql语句value是该语句的SQLiteParameter[]</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
conn.Open();
using (SQLiteTransaction trans = conn.BeginTransaction())
{
SQLiteCommand cmd = new SQLiteCommand();
try
{
//循环
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
trans.Commit();
}
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// 执行一条计算查询结果语句返回查询结果object
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果object</returns>
public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
using (SQLiteCommand cmd = new SQLiteCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
}
}
}
/// <summary>
/// 执行查询语句返回SQLiteDataReader
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SQLiteDataReader</returns>
public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms)
{
SQLiteConnection connection = new SQLiteConnection(connectionString);
SQLiteCommand cmd = new SQLiteCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
SQLiteDataReader myReader = cmd.ExecuteReader();
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SQLite.SQLiteException e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 执行查询语句返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms)
{
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SQLite.SQLiteException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SQLiteParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
}
#endregion
}
}

View File

@@ -0,0 +1,265 @@
//----------------------------------------------------------------
// Copyright (C) 2000-2001 Microsoft Corporation
// All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
// FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------
namespace SystemFramework
{
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
/// <summary>
/// A class to help with error checking and automatic logging
/// of asserts and conditional checks.
/// <remarks>
/// This class works with displays system assert dialogs
/// as well as writing to the application log with the
/// ApplicationLog class. There is no instance data associated
/// with this class.
/// </remarks>
/// </summary>
public class ApplicationAssert
{
// #if !DEBUG
/// <value>
/// A LineNumber constant to be used when not in a debug build
/// so that ApplicationAssert. LineNumber is always a valid expression.
/// <remarks>
/// This allows us to pass ApplicationAssert.LineNumber with good debug
/// functionality and minimal runtime overhead.
/// </remarks>
/// </value>
// public const int LineNumber = 0;
// #else
static string currentTrace;
/// <value>Property LineNumber is used to get the current line number in the calling function.</value>
/// <remarks>
/// This should be called in a parameter list to get accurate
/// information about the line number before the Check* functions
/// are called. If we wait until the Check* functions themselves
/// to retrieve this information, then the stack trace indicates
/// the next executable line, which is only marginally useful
/// information. This function is compiled out in debug builds in
/// favor of the LineNumber constant.
/// Returns LineNumber, or 0 on failure.
/// </remarks>
public static int LineNumber
{
get
{
try
{
//
// Get the trace information with file information by skipping
// this function and then reading the top stack frame.
//
return (new StackTrace(1, true)).GetFrame(0).GetFileLineNumber();
}
catch
{
}
return 0;
}
}
//#endif
/// <summary>
/// Check the given condition and show an assert dialog when the
/// desktop is interactive.
/// <remarks>
/// Log the assertion at a warning level in case the desktop is not
/// interactive. The text will always contain full stack trace
/// information and will show the location of the error condition if
/// the source code is available.
/// </remarks>
/// <param name="condition">An expression to be tested for True</param>
/// <param name="errorText">The message to display</param>
/// <param name="lineNumber">
/// The line of the current error in the function. See
/// GenerateStackTrace for more information.
/// </param>
/// </summary>
//[ConditionalAttribute("DEBUG")]
public static void Check(bool condition, String errorText, int lineNumber)
{
if ( !condition )
{
String detailMessage = String.Empty;
StringBuilder strBuilder;
GenerateStackTrace(lineNumber);
detailMessage = currentTrace;
strBuilder = new StringBuilder();
strBuilder.Append("Assert: ").Append("\r\n").Append(errorText).Append("\r\n").Append(detailMessage);
ApplicationLog.WriteLog(strBuilder.ToString());
System.Diagnostics.Debug.Fail(errorText, detailMessage);
}
}
/// <summary>
///
/// </summary>
/// <param name="errorText"></param>
/// <param name="lineNumber"></param>
/// <returns></returns>
public static string GetDetailMessage(String errorText, int lineNumber)
{
String detailMessage = String.Empty;
StringBuilder strBuilder;
GenerateStackTrace(lineNumber);
detailMessage = currentTrace;
strBuilder = new StringBuilder();
strBuilder.Append("Assert: ").Append("\r\n").Append(errorText).Append("\r\n").Append(detailMessage);
return strBuilder.ToString();
}
/// <summary>
/// Verify that a required condition holds.
/// <remarks>
/// Show an assert dialog in a DEBUG build before throwing an
/// ApplicationException. It is assumed that the exception will be
/// handled or logged, so this does not log a warning for the assertion
/// like the Check function, which does not actually throw.
/// </remarks>
/// <param name="condition">An expression to be tested for True</param>
/// <param name="errorText">The message to display</param>
/// <param name="lineNumber">
/// The line of the current error in the function. See
/// GenerateStackTrace for more information.
/// </param>
/// <exception class="System.ApplicationException">
/// The checked condition failed.
/// </exception>
/// </summary>
public static void CheckCondition(bool condition, String errorText, int lineNumber)
{
//Test the condition
if ( !condition )
{
//Assert and throw if the condition is not met
String detailMessage;
GenerateStackTrace(lineNumber);
detailMessage = currentTrace;
Debug.Fail(errorText, detailMessage);
throw new ApplicationException(errorText);
}
}
/// <summary>
/// Generate a stack trace to display/log with the assertion text.
/// <remarks>
/// The trace information includes file and line number information
/// if its available, as well as a copy of the line of text if
/// the source code is available. This function is only included in
/// DEBUG builds of the application.
/// </remarks>
/// <param name="lineNumber">
/// The line of the current error in the function. This
/// value should be retrieved by call Application.LineNumber
/// in the parameter list of any of the Check* functions. If
/// LineNumber is not provided,then the next executable line is used.
/// </param>
/// </summary>
[ConditionalAttribute("DEBUG")]
private static void GenerateStackTrace(int lineNumber)
{
currentTrace = String.Empty;
// #if DEBUG
StringBuilder message; //Used for smart string concatenation
String fileName; //The source file name
int currentLine; //The line to process in the source file
String sourceLine; //The line from the source file
StreamReader fileStream = null; //The reader used to scan the source file
bool openedFile = false;
StackTrace curTrace;
StackFrame curFrame;
message = new StringBuilder();
//New StackTrace should never fail, but Try/Catch to be rock solid.
try
{
//Get a new stack trace with line information. Skip the first function
// and second functions (this one, and the calling Check* function)
curTrace = new StackTrace(2, true);
try
{
//
// Get the first retrieved stack frame and attempt to get
// file information from the trace, then open the file
// and find the specified line. Display as much information
// as possible if this is not supported.
//
curFrame = curTrace.GetFrame(0);
//Retrieve and add File/Line information. Note that we only
//proceed if both of these are available.
if ((String.Empty != (fileName = curFrame.GetFileName())) &&
(0 <= (currentLine = (lineNumber != 0) ? lineNumber : curFrame.GetFileLineNumber())))
{
//Append File name and line number
message.Append(fileName).Append(", Line: ").Append(currentLine);
//Append the actual code if we can find the source file
fileStream = new StreamReader(fileName);
openedFile = true;
do
{
sourceLine = fileStream.ReadLine();
--currentLine;
} while (currentLine != 0);
message.Append("\r\n");
if (lineNumber != 0)
{
message.Append("Current executable line:");
}
else
{
message.Append("\r\n").Append("Next executable line:");
}
message.Append("\r\n").Append(sourceLine.Trim());
}
}
catch
{
//Ignore errors, just show as much as we can
}
finally
{
//Always close the file
if (openedFile) fileStream.Close();
}
//Retrieve the final string
currentTrace = message.ToString();
}
catch
{
//Nothing to do, just get out of here with the default (empty) return value
}
// #endif
}
} // class ApplicationAssert
} // namespace Duwamish7.SystemFramework

View File

@@ -0,0 +1,219 @@
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace SystemFramework
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class ApplicationLog
{
//This object is added as a debug listener.
private static StreamWriter debugWriter;
/// <summary>
///
/// </summary>
/// <param name="ex"></param>
/// <param name="catchInfo"></param>
/// <returns></returns>
public static String FormatException(Exception ex, String catchInfo)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.Append("Message:"+DateTime.Now.ToString()+"\r\n");
if (catchInfo != String.Empty)
{
strBuilder.Append(catchInfo).Append("\r\n");
}
strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace).Append("\r\n").Append(ex.Source).Append("\r\n").Append(DateTime.Now.ToString()).Append("\r\n\r\n");
ApplicationAssert.GetDetailMessage(strBuilder.ToString(), ApplicationAssert.LineNumber);
return strBuilder.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="ex"></param>
/// <param name="catchInfo"></param>
public static void WriteLog( Exception ex, String catchInfo)
{
WriteLog(FormatException( ex, catchInfo));
}
/// <summary>
/// Determine where a string needs to be written based on the
/// configuration settings and the error level.
/// <param name="messageText">The string to be logged.</param>
/// </summary>
public static void WriteLog( String messageText)
{
//
// Be very careful by putting a Try/Catch around the entire routine.
// We should never throw an exception while logging.
//
try
{
//
// Write the message to the trace file
//
//Make sure a tracing file is specified.
if (debugWriter != null)
{
lock(debugWriter)
{
//写入Log文件
Debug.WriteLine("Time:"+DateTime.Now.ToString()+"\r\n"+messageText);
debugWriter.Flush();
//显示到屏幕
// Trace.WriteLine(messageText);
// Trace.Flush();
}
}
}
catch {} //Ignore any exceptions.
}
static ApplicationLog()
{
//Protect thread locks with Try/Catch to guarantee that we let go of the lock.
try
{
//See if there is a debug configuration file specified and set up the
// tracing variables.
bool clearSettings = true;
try
{
String tracingFile = System.Configuration.ConfigurationManager.AppSettings.GetValues("TracingTraceFile")[0].ToString();
FileInfo file = new FileInfo(tracingFile);
debugWriter = new StreamWriter(file.Open(FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
Debug.Listeners.Add(new TextWriterTraceListener(debugWriter));
TextWriterTraceListener consoleWriter = new
TextWriterTraceListener(System.Console.Out);
Trace.Listeners.Add(consoleWriter);
clearSettings = false;
}
catch
{
//Ignore the error
}
//Use default (empty) values if something went wrong
if (clearSettings)
{
debugWriter = null;
}
}
finally
{
//Remove the lock from the class object
//Monitor.Exit(myType);
}
}
private static void GenerateStackTrace(int lineNumber, out String currentTrace)
{
currentTrace = String.Empty;
StringBuilder message; //Used for smart string concatenation
String fileName; //The source file name
int currentLine; //The line to process in the source file
String sourceLine; //The line from the source file
StreamReader fileStream = null; //The reader used to scan the source file
bool openedFile = false;
StackTrace curTrace;
StackFrame curFrame;
message = new StringBuilder();
//New StackTrace should never fail, but Try/Catch to be rock solid.
try
{
//Get a new stack trace with line information. Skip the first function
// and second functions (this one, and the calling Check* function)
curTrace = new StackTrace(2, true);
try
{
//
// Get the first retrieved stack frame and attempt to get
// file information from the trace, then open the file
// and find the specified line. Display as much information
// as possible if this is not supported.
//
curFrame = curTrace.GetFrame(0);
//Retrieve and add File/Line information. Note that we only
//proceed if both of these are available.
if ((String.Empty != (fileName = curFrame.GetFileName())) &&
(0 <= (currentLine = (lineNumber != 0) ? lineNumber : curFrame.GetFileLineNumber())))
{
//Append File name and line number
message.Append(fileName).Append(", Line: ").Append(currentLine);
//Append the actual code if we can find the source file
fileStream = new StreamReader(fileName);
openedFile = true;
do
{
sourceLine = fileStream.ReadLine();
--currentLine;
} while (currentLine != 0);
message.Append("\r\n");
if (lineNumber != 0)
{
message.Append("Current executable line:");
}
else
{
message.Append("\r\n").Append("Next executable line:");
}
message.Append("\r\n").Append(sourceLine.Trim());
}
}
catch
{
//Ignore errors, just show as much as we can
}
finally
{
//Always close the file
if (openedFile) fileStream.Close();
}
//Retrieve the final string
currentTrace = message.ToString();
}
catch
{
//Nothing to do, just get out of here with the default (empty) return value
}
}
}
}

View File

@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;
using System.ComponentModel;
namespace DataLinkMesWork
{
/// <summary>
///
/// </summary>
public class Reflection
{
/// <summary>
/// 通过反射调用动态连接库方法
/// </summary>
/// <param name="assembly">程序集(DLL)</param>
/// <param name="Namespace">命名空间名称,如果无命名空间写“”</param>
/// <param name="Classname">类名</param>
/// <param name="Method">方法名</param>
/// <param name="Paramsters">函数参数数组</param>
static public string ReflectionMethod(Assembly assembly, string Namespace, string Classname, string Method, object[] Paramsters)
{
try
{
Type t;
//类
if (Namespace == "")
{
t = assembly.GetType(Classname);
}
else
{
t = assembly.GetType(Namespace + "." + Classname);
}
if (t == null)
{
return "类不存在";
}
////方法
MethodInfo mi = t.GetMethod(Method); //获取方法
if (mi == null)
{
return "方法不存在";
}
ParameterInfo[] paramsInfo = mi.GetParameters();
for (int i = 0; i < paramsInfo.Length; i++)
{
Type tType = paramsInfo[i].ParameterType;
//改变参数类型
Paramsters[i]= SD_ChanageType(Paramsters[i],tType);
}
/// 建一个实例化的类
object instanceObject = Activator.CreateInstance(t);
mi.Invoke(instanceObject, Paramsters);
return "ok";
}
catch(Exception err)
{
return err.ToString();
}
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="convertsionType"></param>
/// <returns></returns>
public static object SD_ChanageType(object value, Type convertsionType)
{
//判断convertsionType类型是否为泛型因为nullable是泛型类,
if (convertsionType.IsGenericType &&
//判断convertsionType是否为nullable泛型类
convertsionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null || value.ToString().Length == 0)
{
return null;
}
//如果convertsionType为nullable类声明一个NullableConverter类该类提供从Nullable类到基础基元类型的转换
NullableConverter nullableConverter = new NullableConverter(convertsionType);
//将convertsionType转换为nullable对的基础基元类型
convertsionType = nullableConverter.UnderlyingType;
}
return Convert.ChangeType(value, convertsionType);
}
}
}

View File

@@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using System.Text;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
using SystemFramework;
namespace DataLinkMesWork
{
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void DelegateClassHandle_UDPServerReceive(object sender, UDPServerReceiveEvetnArgs e);
/// <summary>
///
/// </summary>
public class UDPServerReceiveEvetnArgs : EventArgs
{
object tagKey = 0;
object opName = "";
object tagValue = 0;
object tagQuality = 0;
/// <summary>
///
/// </summary>
public UDPServerReceiveEvetnArgs()
{ }
/// <summary>
///
/// </summary>
public object TagKey
{
get { return this.tagKey; }
set { this.tagKey = value; }
}
/// <summary>
///
/// </summary>
public object TagValue
{
get { return this.tagValue; }
set { this.tagValue = value; }
}
/// <summary>
///
/// </summary>
public object OpName
{
get { return this.opName; }
set { this.opName = value; }
}
/// <summary>
///
/// </summary>
public object TagQuality
{
get { return this.tagQuality; }
set { this.tagQuality = value; }
}
}
/// <summary>
///
/// </summary>
public class TagDataUDPServerReceive
{
private object tagKey;
/// <summary>
///
/// </summary>
public object TagKey
{
get { return tagKey; }
set { tagKey = value; }
}
private object tagValue;
/// <summary>
///
/// </summary>
public object TagValue
{
get { return tagValue; }
set { tagValue = value; }
}
/// <summary>
///
/// </summary>
public event DelegateClassHandle_UDPServerReceive TagDataOnChange;
/// <summary>
///
/// </summary>
/// <param name="e"></param>
public void InvokeTagData(UDPServerReceiveEvetnArgs e)
{
if (TagDataOnChange != null)
{
TagDataOnChange(this, e);
}
}
/// <summary>
///
/// </summary>
/// <param name="tagValue"></param>
public void InvokeTagData(object tagValue)
{
if (TagDataOnChange != null)
{
UDPServerReceiveEvetnArgs e = new UDPServerReceiveEvetnArgs();
e.TagValue = tagValue;
TagDataOnChange(this, e);
}
}
}
/// <summary>
/// 使用的接收端口
/// </summary>
public class UDPServerReceive
{
Thread mythread;
//使用的接收端口
/// <summary>
/// 端口号
/// </summary>
private int port;
/// <summary>
/// udp连接对象
/// </summary>
private UdpClient udpclient;
/// <summary>
///
/// </summary>
public TagDataUDPServerReceive m_TagDataUDPServerReceive;
/// <summary>
///
/// </summary>
/// <param name="port_In"></param>
public UDPServerReceive(int port_In)
{
m_TagDataUDPServerReceive = new TagDataUDPServerReceive();
port = port_In;
//创建一个线程接收接收远程主机发来的信息
mythread = new Thread(new ThreadStart(RecData));
//将线程设为后台运行
mythread.IsBackground = true;
mythread.Start();
}
/// <summary>
/// 开始接受新的端口数据
/// </summary>
/// <param name="port_In"></param>
public void Start(int port_In)
{
port = port_In;
if (mythread != null)
{
try
{
if (udpclient != null)
{
udpclient.Close();
}
mythread.Abort();
}
catch { }
}
//创建一个线程接收接收远程主机发来的信息
mythread = new Thread(new ThreadStart(RecData));
//将线程设为后台运行
mythread.IsBackground = true;
mythread.Start();
}
/// <summary>
/// 开始接受新的端口数据
/// </summary>
/// <param name="port_In"></param>
public void Close(int port_In)
{
port = port_In;
if (mythread != null)
{
try
{
if (udpclient != null)
{
udpclient.Close();
}
//mythread.Abort();
}
catch { }
}
}
/// <summary>
/// 在后台运行的接收线程
/// </summary>
private void RecData()
{
try
{
//本机指定端口接收
udpclient = new UdpClient(port);
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, "RecData:new UdpClient(port)=" + port.ToString());
}
IPEndPoint remote = null;
while (true)
{
try
{
//接收从远程主机发送过来的信息
string sendMessage;
//关闭udpclient时此句会产生异常
byte[] bytes = udpclient.Receive(ref remote);
string strSource = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
sendMessage = strSource;
m_TagDataUDPServerReceive.InvokeTagData(sendMessage);
}
catch
{
break;
}
}
}
}
}

View File

@@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.Text;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;
using SystemFramework;
namespace DataLinkMesWork
{
/// <summary>
/// 利用UDP向端口port发送数据
/// </summary>
public class UDPClientSend
{
/// <summary>
/// 向指定IP发送UDP
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="text"></param>
public static void Send(string ip, int port, string text)
{
UdpClient myUdpclient = new UdpClient();
string sendMessage;
try
{
DateTime m_DateTime = DateTime.Now;
IPEndPoint iep;
if (ip == "")
{
iep = new IPEndPoint(IPAddress.Broadcast, port);
}
else
{
iep = new IPEndPoint(IPAddress.Parse(ip), port);
}
sendMessage = text;
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
myUdpclient.Send(bytes, bytes.Length, iep);
myUdpclient.Close();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, "UDPClientSend Send");
}
finally
{
myUdpclient.Close();
}
}
/// <summary>
/// 利用UDP向端口port发送数据
/// </summary>
/// <param name="port"></param>
/// <param name="opName"></param>
/// <param name="text"></param>
public static void Send(int port, string text)
{
UdpClient myUdpclient = new UdpClient();
string sendMessage;
try
{
DateTime m_DateTime = DateTime.Now;
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
sendMessage = text;
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
myUdpclient.Send(bytes, bytes.Length, iep);
myUdpclient.Close();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, "UDPClientSend Send");
}
finally
{
myUdpclient.Close();
}
}
/// <summary>
/// 向指定端口发生UDP广播
/// </summary>
/// <param name="port"></param>
/// <param name="text"></param>
public static void Send_ALL(int port, string text)
{
UdpClient myUdpclient = new UdpClient();
string sendMessage;
try
{
DateTime m_DateTime = DateTime.Now;
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
sendMessage = text;
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
myUdpclient.Send(bytes, bytes.Length, iep);
myUdpclient.Close();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, "UDPClientSend Send");
}
finally
{
myUdpclient.Close();
}
}
/// <summary>
/// 利用UDP向端口port发送数据
/// </summary>
/// <param name="port"></param>
/// <param name="opName"></param>
/// <param name="text"></param>
public static void Send(int port,string opName, string text)
{
UdpClient myUdpclient = new UdpClient();
if (opName == null)
opName = "OpName";
string sendMessage;
try
{
DateTime m_DateTime = DateTime.Now;
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
sendMessage = text;
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
myUdpclient.Send(bytes, bytes.Length, iep);
myUdpclient.Close();
if (ApplicationConfig.IsUsingUdpMonitor == 1)
{
if (port != ApplicationConfig.DupPort_Recieve_Monitor)
{
sendMessage = "Send?" + ApplicationConfig.IPAddress + "?" + port.ToString() + "?" + opName+"?" + text + "?" + m_DateTime.ToString("G") + "." + m_DateTime.Millisecond.ToString();
UdpClient myUdpclientMonitor = new UdpClient();
iep = new IPEndPoint(IPAddress.Broadcast, ApplicationConfig.DupPort_Recieve_Monitor);
bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
myUdpclientMonitor.Send(bytes, bytes.Length, iep);
myUdpclientMonitor.Close();
}
}
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, "UDPClientSend Send");
}
finally
{
myUdpclient.Close();
}
}
/// <summary>
/// 利用监控端口41199发送数据
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="opName"></param>
/// <param name="text"></param>
public static void SendToMonitor(string ip,int port, string opName, string text)
{
UdpClient myUdpclient = new UdpClient();
string sendMessage;
try
{
DateTime m_DateTime = DateTime.Now;
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, ApplicationConfig.DupPort_Recieve_Monitor);
sendMessage = "Receive?" + ip + "?" + port.ToString() + "?" + opName + "?" + text + "?" + m_DateTime.ToString("G") + "." + m_DateTime.Millisecond.ToString();
byte[] bytes;
bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);
myUdpclient.Send(bytes, bytes.Length, iep);
myUdpclient.Close();
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, "UDPClientSend Send");
}
finally
{
myUdpclient.Close();
}
}
}
}

View File

@@ -0,0 +1,416 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Specialized;
using System.Data.OleDb;
using SystemFramework;
//using SystemFramework;
namespace DataLinkMesWork
{
/// <summary>
/// 数据访问类——提供通用的数据访问方法
/// </summary>
public partial class SQLCommon
{
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="dt">查询结果记录集</param>
/// <param name="oleDbParameter"></param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataTable_OleDb_Insert(string sql, string connectionString, DataTable dt, ref OleDbParameter[] oleDbParameter, out string errorMessage)
{
bool result = false;
errorMessage = "";
try
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
using (OleDbDataAdapter dsCommand = new OleDbDataAdapter())
{
dsCommand.InsertCommand = new OleDbCommand(sql, conn);
for (int i = 0; i < oleDbParameter.Length; i++)
{
oleDbParameter[i].IsNullable = true;
dsCommand.InsertCommand.Parameters.Add(oleDbParameter[i]);
}
if (dt == null) return false;
dt.AcceptChanges();
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i].SetAdded();
}
dsCommand.Update(dt);
}
dt.AcceptChanges();
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteDataTable_OleDb\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\n连接字符串\r\n" + connectionString);
}
return result;
}
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="dt">查询结果记录集</param>
/// <param name="oleDbParameter">参数</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataTable_OleDb_Update(string sql, string connectionString, DataTable dt, ref OleDbParameter[] oleDbParameter, out string errorMessage)
{
bool result = false;
errorMessage = "";
//dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
using (OleDbDataAdapter dsCommand = new OleDbDataAdapter())
{
dsCommand.UpdateCommand = new OleDbCommand(sql, conn);
for (int i = 0; i < oleDbParameter.Length; i++)
{
dsCommand.UpdateCommand.Parameters.Add(oleDbParameter[i]);
}
if (dt == null) return false;
dt.AcceptChanges();
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i].SetModified();//.SetAdded();
}
dsCommand.Update(dt);
}
dt.AcceptChanges();
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteDataTable_OleDb\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 用于 Excel Access
/// 执行标准SQL语句不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql">标准SQL语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteNonQuery_OleDb(string sql, string connectionString, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery_OleDb\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}
return result;
}
/// <summary>
/// 用于 Excel Access
/// 执行标准SQL语句集合不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql"></param>
/// <param name="connectionString"></param>
/// <param name="errorMessage"></param>
/// <returns></returns>
public static bool ExecuteNonQuery_OleDb(StringCollection sql, string connectionString, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
for (int i = 0; i < sql.Count; i++)
{
using (OleDbCommand cmd = new OleDbCommand(sql[i].ToString(), conn))
{
cmd.ExecuteNonQuery();
}
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery_OleDb\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 用于 Excel Access
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="ds">查询结果记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataset_OleDb(string sql, string connectionString, out DataSet ds, out string errorMessage)
{
bool result = false;
errorMessage = "";
ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
using (OleDbDataAdapter dsCommand = new OleDbDataAdapter())
{
dsCommand.SelectCommand = new OleDbCommand(sql, conn);
conn.Open();
dsCommand.Fill(ds);
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteDataset_OleDb(返回DataSet)\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="dt">查询结果记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataTable_OleDb(string sql, string connectionString, out DataTable dt, out string errorMessage)
{
bool result = false;
errorMessage = "";
dt = new DataTable("TableName");
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
using (OleDbDataAdapter dsCommand = new OleDbDataAdapter())
{
dsCommand.SelectCommand = new OleDbCommand(sql, conn);
dsCommand.Fill(dt);
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteDataTable_OleDb\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}
return result;
}
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="ds">查询结果记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataTable_OleDb(string sql, string connectionString, out DataSet ds, out string errorMessage)
{
bool result = false;
errorMessage = "";
ds = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
try
{
conn.Open();
using (OleDbDataAdapter dsCommand = new OleDbDataAdapter())
{
dsCommand.SelectCommand = new OleDbCommand(sql, conn);
dsCommand.Fill(ds);
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteDataTable_OleDb(返回DataSet)\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 返回符合条件的记录行数
/// </summary>
/// <param name="sql"></param>
/// <param name="connectionString"></param>
/// <param name="count"></param>
/// <param name="errorMessage"></param>
/// <returns></returns>
public static bool ExecuteOutNum_OleDb(string sql, string connectionString, out int count, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
count = 0;
try
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
object obj = cmd.ExecuteScalar();
if (obj != null)
{
count = Convert.ToInt32(cmd.ExecuteScalar().ToString());
}
else
count = 0;
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteOutNum\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 增加记录,同时返回自动编号
/// </summary>
/// <param name="sql"></param>
/// <param name="connectionString"></param>
/// <param name="newID"></param>
/// <returns></returns>
public static bool ExecuteNonQuery_newID_OleDb(string sql, string connectionString, out long newID)
{
string errorMessage;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
newID = 0;
try
{
conn.Open();
using (OleDbTransaction myTransaction = conn.BeginTransaction(IsolationLevel.ReadCommitted))
{
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
myTransaction.Commit();
cmd.ExecuteNonQuery();
cmd.CommandText = "select @@identity as id";
newID = Convert.ToInt64(cmd.ExecuteScalar());
}
}
return true;
}
catch (Exception e)
{
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteOutNum\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
return false;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}
}
}

View File

@@ -0,0 +1,5 @@
internal class ContentResult
{
public object Content { get; set; }
public string ContentType { get; set; }
}

View File

@@ -0,0 +1,218 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Data.OleDb;
//using SystemFramework;
namespace DataLinkMesWork
{
/// <summary>
///
/// </summary>
public partial class DataAccess
{
/// <summary>
/// 更新Access数据
/// </summary>
/// <param name="sql"></param>
/// <param name="dt"></param>
/// <param name="oleDbParameter"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Update(string sql,DataTable dt, ref OleDbParameter[] oleDbParameter)
{
string errorMessage;
return SQLCommon.ExecuteDataTable_OleDb_Update(sql, ApplicationConfig.dbConnectionString_Access, dt, ref oleDbParameter, out errorMessage);
}
/// <summary>
/// 增加Access数据
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="dt"></param>
/// <param name="oleDbParameter"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Insert_Access(string sql, string filename, DataTable dt, ref OleDbParameter[] oleDbParameter)
{
string errorMessage;
string connectionString = ConnectString_OleDb_Access(filename);
return SQLCommon.ExecuteDataTable_OleDb_Insert(sql, connectionString, dt, ref oleDbParameter, out errorMessage);
}
/// <summary>
/// 用于 Access
/// 执行标准SQL语句不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql"></param>
/// <param name="filename">Excel Access文件</param>
/// <returns></returns>
public static bool ExecuteSQL_OleDb_Access(string filename, string sql)
{
string ErrorMessage;
string dbConnectionString_Access;
dbConnectionString_Access = ConnectString_OleDb_Access(filename);
return SQLCommon.ExecuteNonQuery_OleDb(sql, dbConnectionString_Access, out ErrorMessage);
}
/// <summary>
/// 用于 Excel Access
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Access(string sql, string filename, out DataTable dt)
{
string ErrorMessage;
string strConnectionstring;
strConnectionstring = ConnectString_OleDb_Access(filename);
ErrorMessage = "";
return SQLCommon.ExecuteDataTable_OleDb(sql, strConnectionstring, out dt, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="strConnectionstring"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Access_Connectionstring(string sql, string strConnectionstring, out DataTable dt)
{
string ErrorMessage;
ErrorMessage = "";
return SQLCommon.ExecuteDataTable_OleDb(sql, strConnectionstring, out dt, out ErrorMessage);
} /// <summary>
/// 根据Access文件名称获得Access连接字符串
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string ConnectString_OleDb_Access(string filename)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename;
return strConn;
}
/// <summary>
/// 用于 Access
/// 执行标准SQL语句不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql"></param>
/// <param name="ConnectionString_Access"></param>
/// <returns></returns>
public static bool ExecuteSQL_OleDb_Access_ConnectionString_Access(string sql, string ConnectionString_Access)
{
string ErrorMessage;
return SQLCommon.ExecuteNonQuery_OleDb(sql, ConnectionString_Access, out ErrorMessage);
}
/// <summary>
/// 用于 Access
/// 执行标准SQL语句不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static bool ExecuteSQL_OleDb_Access(string sql)
{
string ErrorMessage;
return SQLCommon.ExecuteNonQuery_OleDb(sql, ApplicationConfig.ConnectionString_Access, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static bool ExecuteSQL_OleDb_Access(StringCollection sql)
{
string ErrorMessage;
return SQLCommon.ExecuteNonQuery_OleDb(sql, ApplicationConfig.ConnectionString_Access, out ErrorMessage);
}
/// <summary>
/// 用于 Access
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Access(string sql, out DataTable dt)
{
string ErrorMessage;
return SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.ConnectionString_Access, out dt, out ErrorMessage);
}
/// <summary>
/// 返回count
/// </summary>
/// <param name="sql"></param>
/// <param name="count"></param>
/// <returns></returns>
public static bool ExecuteOutNum_OleDb_Access(string sql, out int count)
{
string errorMessage;
return SQLCommon.ExecuteOutNum_OleDb(sql, ApplicationConfig.ConnectionString_Access, out count, out errorMessage);
}
/// <summary>
/// 返回count
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="count"></param>
/// <returns></returns>
public static bool ExecuteOutNum_OleDb_Access(string sql, string filename, out int count)
{
string errorMessage;
string connectionString = ConnectString_OleDb_Access(filename);
return SQLCommon.ExecuteOutNum_OleDb(sql, connectionString, out count, out errorMessage);
}
/// <summary>
/// 增加Access数据
/// </summary>
/// <param name="sql"></param>
/// <param name="dt"></param>
/// <param name="oleDbParameter"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Insert_Access(string sql, DataTable dt, ref OleDbParameter[] oleDbParameter)
{
string errorMessage;
return SQLCommon.ExecuteDataTable_OleDb_Insert(sql, ApplicationConfig.ConnectionString_Access, dt, ref oleDbParameter, out errorMessage);
}
/// <summary>
/// 执行Insert 命令,同时返回自动编号
/// 保存到Access数据库
/// </summary>
/// <param name="sql"></param>
/// <param name="newID"></param>
public static bool ExecuteNonQuery_newID_OleDb(string sql, out long newID)
{
return SQLCommon.ExecuteNonQuery_newID_OleDb(sql, ApplicationConfig.ConnectionString_Access, out newID);
}
/// <summary>
/// 执行Insert 命令,同时返回自动编号
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="newID"></param>
public static bool ExecuteNonQuery_newID_OleDb(string sql,string filename, out long newID)
{
string strConnectionstring;
strConnectionstring = ConnectString_OleDb_Access(filename);
return SQLCommon.ExecuteNonQuery_newID_OleDb(sql, strConnectionstring, out newID);
}
}
}

View File

@@ -0,0 +1,111 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Data.OleDb;
//using SystemFramework;
namespace DataLinkMesWork
{
public partial class DataAccess
{
/// <summary>
/// 获得Excel连接
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string ConnectString_OleDb(string filename)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=\"" + filename + "\""; ;
strConn += ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\"";
return strConn;
}
/// <summary>
///
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static OleDbConnection getConn_OleDb(string filename)
{
string strConnectionstring = ConnectString_OleDb(filename);
OleDbConnection conn = new OleDbConnection(strConnectionstring);
conn.Open();
return conn;
}
/// <summary>
/// 增加Excel数据
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="dt"></param>
/// <param name="oleDbParameter"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Insert_Excel(string sql, string filename, DataTable dt, ref OleDbParameter[] oleDbParameter)
{
string errorMessage;
string connectionString = ConnectString_OleDb(filename);
return SQLCommon.ExecuteDataTable_OleDb_Insert(sql, connectionString, dt, ref oleDbParameter, out errorMessage);
}
/// <summary>
/// 用于 Excel Access
/// 执行标准SQL语句不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql"></param>
/// <param name="filename">Excel Access文件</param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteSQL_OleDb(string sql, string filename, out string ErrorMessage)
{
string strConnectionstring;
strConnectionstring = ConnectString_OleDb(filename);
ErrorMessage = "";
return SQLCommon.ExecuteNonQuery_OleDb(sql, strConnectionstring, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteSQL_OleDb(StringCollection sql, string filename, out string ErrorMessage)
{
string strConnectionstring;
strConnectionstring = ConnectString_OleDb(filename);
ErrorMessage = "";
return SQLCommon.ExecuteNonQuery_OleDb(sql, strConnectionstring, out ErrorMessage);
}
/// <summary>
/// 用于 Excel Access
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql"></param>
/// <param name="filename"></param>
/// <param name="dt"></param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb(string sql, string filename, out DataTable dt, out string ErrorMessage)
{
string strConnectionstring;
strConnectionstring = ConnectString_OleDb(filename);
ErrorMessage = "";
return SQLCommon.ExecuteDataTable_OleDb(sql, strConnectionstring, out dt, out ErrorMessage);
}
}
}

View File

@@ -0,0 +1,169 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Data.OleDb;
//using SystemFramework;
namespace DataLinkMesWork
{
public partial class DataAccess
{
/// <summary>
/// 增加SqlServer数据
/// </summary>
/// <param name="sql"></param>
/// <param name="dt"></param>
/// <param name="oleDbParameter"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Insert_SqlServer(string sql, DataTable dt, ref OleDbParameter[] oleDbParameter)
{
string errorMessage;
return SQLCommon.ExecuteDataTable_OleDb_Insert(sql, ApplicationConfig.ConnectionString_MES, dt, ref oleDbParameter, out errorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="count"></param>
/// <returns></returns>
public static bool ExecuteOutNum(string sql, out int count)
{
string errorMessage;
return SQLCommon.ExecuteOutNum(sql, ApplicationConfig.ConnectionString_MES, out count, out errorMessage);
}
/// <summary>
/// 提供通用的调用存储过程的方法(更新数据)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="dt">增加数据的数据表</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure_Update(string procedureName, ref SqlParameter[] sqlParameters, DataTable dt)
{
string errorMessage;
return SQLCommon.ExecuteStoredProcedure_Update(procedureName, ApplicationConfig.ConnectionString_MES, ref sqlParameters, dt, out errorMessage);
}
/// <summary>
/// 直接执行制定SQL语句.用于无返回条件的SQL语句执行Insert ,delete update等。
/// </summary>
/// <param name="sql"></param>
/// <returns>成功返回True / 失败返回False</returns>
public static bool ExecuteSQL(string sql)
{
string ErrorMessage;
return SQLCommon.ExecuteNonQuery(sql, ApplicationConfig.ConnectionString_MES, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static bool ExecuteSQL(StringCollection sql)
{
string ErrorMessage;
return SQLCommon.ExecuteNonQuery(sql, ApplicationConfig.ConnectionString_MES, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParameters"></param>
/// <param name="tb"></param>
/// <returns></returns>
public static bool ExecuteSQL(string sql, ref SqlParameter[] sqlParameters, DataTable tb)
{
string ErrorMessage;
return SQLCommon.ExecuteSQL(sql, ref sqlParameters, ApplicationConfig.ConnectionString_MES, tb, out ErrorMessage);
}
/// <summary>
/// 直接执行制定SQL语句.用于无返回条件的SQL语句执行Insert ,delete update等。
/// </summary>
/// <param name="sql"></param>
/// <param name="strConnectionstring"></param>
/// <param name="ErrorMessage"></param>
/// <returns>成功返回True / 失败返回False</returns>
public static bool ExecuteSQL(string sql, string strConnectionstring, out string ErrorMessage)
{
ErrorMessage = "";
return SQLCommon.ExecuteNonQuery(sql, strConnectionstring, out ErrorMessage);
}
/// <summary>
/// 增加记录后,返回自动编号
/// </summary>
/// <param name="sql"></param>
/// <param name="newID"></param>
/// <returns></returns>
public static bool ExecuteNonQuery_newID(string sql, out long newID)
{
return SQLCommon.ExecuteNonQuery_newID(sql, out newID);
}
/// <summary>
/// 执行指定SQL语句用于执行查询后返回记录集
/// </summary>
/// <param name="sql"></param>
/// <param name="strConnectionstring"></param>
/// <param name="ds">返回记录集</param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteDataSet(string sql, string strConnectionstring, out DataSet ds, out string ErrorMessage)
{
ErrorMessage = "";
return SQLCommon.ExecuteDataset(sql, strConnectionstring, out ds, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="strConnectionstring"></param>
/// <param name="dt"></param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteDataTable(string sql, string strConnectionstring, out DataTable dt, out string ErrorMessage)
{
ErrorMessage = "";
return SQLCommon.ExecuteDataTable(sql, strConnectionstring, out dt, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool ExecuteDataTable(string sql, out DataTable dt)
{
string ErrorMessage = "";
return SQLCommon.ExecuteDataTable(sql, ApplicationConfig.ConnectionString_MES, out dt, out ErrorMessage);
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="strConnectionstring"></param>
/// <param name="dr"></param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteDataReader(string sql, string strConnectionstring, out SqlDataReader dr, out string ErrorMessage)
{
ErrorMessage = "";
return SQLCommon.ExecuteDataReader(sql, strConnectionstring, out dr, out ErrorMessage);
}
}
}

View File

@@ -0,0 +1,67 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using System.Data.OleDb;
using SystemFramework;
//using SystemFramework;
namespace DataLinkMesWork
{
public partial class DataAccess
{
/// <summary>
/// 测试与数据的连接线程
/// </summary>
static Thread threadTestConnection;
/// <summary>
/// 测试与数据的连接
/// </summary>
/// <returns></returns>
public static void TestConnection()
{
try
{
if (threadTestConnection == null)
{
threadTestConnection = new Thread(new ThreadStart(SQLCommon.TestConnection));
threadTestConnection.Start();
}
else
{
threadTestConnection.Abort();
threadTestConnection = null;
threadTestConnection = new Thread(new ThreadStart(SQLCommon.TestConnection));
threadTestConnection.Start();
}
}
catch (Exception err)
{
ApplicationLog.WriteLog(err, err.Source);
}
}
/// <summary>
/// 测试与数据的连接
/// </summary>
/// <returns></returns>
public static void TestConnectionFirst()
{
SQLCommon.TestConnection();
}
}
}

View File

@@ -0,0 +1,439 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Data.OleDb;
//using SystemFramework;
namespace DataLinkMesWork
{
public partial class DataAccess
{
/// <summary>
/// 创建增加数据用表
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static DataTable GetInsertTable(DataTable dt)
{
DataTable dt1;
DataRow row;
dt1 = dt.Clone();
for (int i = 0; i < dt.Rows.Count; i++)
{
row = dt1.NewRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
row[j] = dt.Rows[i][j];
}
dt1.Rows.Add(row);
}
return dt1;
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="ds"></param>
/// <returns></returns>
public static bool ExecuteDataTable_OleDb_Access1(string sql,out DataSet ds)
{
string ErrorMessage ;
return SQLCommon.ExecuteDataTable_OleDb(sql, ApplicationConfig.dbConnectionString_Access, out ds, out ErrorMessage);
}
/// <summary>
/// 获取EXCEL的表 表名字列
/// </summary>
/// <param name="p_ExcelFile">Excel文件</param>
/// <returns>数据表</returns>
public static DataTable GetExcelTableName(string p_ExcelFile)
{
try
{
if (System.IO.File.Exists(p_ExcelFile))
{
OleDbConnection _ExcelConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0\";Data Source=" + p_ExcelFile);
_ExcelConn.Open();
DataTable _Table = _ExcelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
_ExcelConn.Close();
return _Table;
}
return null;
}
catch
{
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="strConnectionstring"></param>
/// <returns></returns>
public static SqlConnection getConn(string strConnectionstring)
{
SqlConnection conn = new SqlConnection(strConnectionstring);
conn.Open();
return conn;
}
/// <summary>
///
/// </summary>
/// <param name="conn"></param>
/// <param name="mTrans"></param>
/// <param name="sql"></param>
public static void TranExecuteNonQuery(SqlConnection conn, SqlTransaction mTrans, string sql)
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Transaction = mTrans;
cmd.ExecuteNonQuery();
}
/// <summary>
/// 执行指定Sql 语句,返回所影响的行数。
/// </summary>
/// <param name="sql">拼接出来的SQL语句。</param>
/// <param name="strConnectionstring"></param>
/// <param name="count">返回所影响的记录条数</param>
/// <param name="ErrorMessage">ErrorMessage</param>
/// <returns>True / False</returns>
public static bool ExecuteSql_count(string sql,string strConnectionstring, out int count,out string ErrorMessage)
{
SqlParameter[] thisParms = new SqlParameter[2];
thisParms[0] = new System.Data.SqlClient.SqlParameter("@sql", sql);
thisParms[0].Direction = ParameterDirection.Input;
thisParms[1] = new System.Data.SqlClient.SqlParameter("@count", SqlDbType.Int, 32);
thisParms[1].Direction = ParameterDirection.Output;
count = 0;
ErrorMessage = "";
if (SQLCommon.ExecuteStoredProcedure("sp_xt_executesql_count", strConnectionstring, ref thisParms, out ErrorMessage))
{
count = Convert.ToInt32(thisParms[1].Value.ToString());
return true;
}
return false;
}
/// <summary>
/// 执行指定插入 Sql 语句返回当前记录的新ID。
/// </summary>
/// <param name="sql">拼接出来的SQL语句。</param>
/// <param name="strConnectionstring"></param>
/// <param name="tablename"></param>
/// <param name="newID">返回当前记录的新ID</param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteSql_newID(string sql,string strConnectionstring, string tablename, out long newID, out string ErrorMessage)
{
SqlParameter[] thisParms = new SqlParameter[3];
thisParms[0] = new System.Data.SqlClient.SqlParameter("@sql", sql);
thisParms[0].Direction = ParameterDirection.Input;
thisParms[1] = new System.Data.SqlClient.SqlParameter("@newID", SqlDbType.BigInt, 64);
thisParms[1].Direction = ParameterDirection.Output;
thisParms[2] = new System.Data.SqlClient.SqlParameter("@tablename", tablename);
thisParms[2].Direction = ParameterDirection.Input;
newID = 0;
ErrorMessage = "";
if (SQLCommon.ExecuteStoredProcedure("sp_xt_insertRecord_newID", strConnectionstring, ref thisParms, out ErrorMessage))
{
newID = Convert.ToInt32(thisParms[1].Value.ToString());
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <param name="strConnectionstring"></param>
/// <param name="tablename"></param>
/// <param name="newID"></param>
/// <param name="ErrorMessage"></param>
/// <returns></returns>
public static bool ExecuteSql_newID(string sql,string strConnectionstring,string tablename, out int newID,out string ErrorMessage)
{
SqlParameter[] thisParms = new SqlParameter[3];
thisParms[0] = new System.Data.SqlClient.SqlParameter("@sql", sql);
thisParms[0].Direction = ParameterDirection.Input;
thisParms[1] = new System.Data.SqlClient.SqlParameter("@newID", SqlDbType.Int, 32);
thisParms[1].Direction = ParameterDirection.Output;
thisParms[2] = new System.Data.SqlClient.SqlParameter("@tablename", tablename);
thisParms[2].Direction = ParameterDirection.Input;
newID = 0;
ErrorMessage = "";
if (SQLCommon.ExecuteStoredProcedure("sp_xt_insertRecord_newID", strConnectionstring, ref thisParms, out ErrorMessage))
{
newID = Convert.ToInt32(thisParms[1].Value.ToString());
return true;
}
return false;
}
/// <summary>
/// 根据输入参数,对指定表进行分页显示
/// </summary>
/// <param name="tbname">要进行分页的表/视图的名称</param>
/// <param name="strConnectionstring"></param>
/// <param name="fieldkey">表或者视图的主键</param>
/// <param name="where">进行过滤的条件</param>
/// <param name="fieldshow">需要显示的字段名称</param>
/// <param name="fieldorder">排序的条件,直接输入字段名 +desc/asc例如id desc,name asc</param>
/// <param name="pagecurrent">当前页的页码</param>
/// <param name="pagesize">每一页的显示的数据量</param>
/// <param name="pagecount">返回页码总数</param>
/// <param name="itemcount">返回数据总数</param>
/// <param name="ds"></param>
/// <param name="ErrorMessage">返回错误</param>
/// <returns>True / False</returns>
public static bool ExecPageQuery(string tbname,string strConnectionstring, string fieldkey, string where, string fieldshow, string fieldorder, int pagecurrent, int pagesize, out int pagecount, out int itemcount,out DataSet ds, out string ErrorMessage)
{
SqlParameter[] thisParms = new SqlParameter[9];
thisParms[0] = new System.Data.SqlClient.SqlParameter("@tbname", tbname);
thisParms[0].Direction = ParameterDirection.Input;
thisParms[1] = new System.Data.SqlClient.SqlParameter("@fieldkey", fieldkey);
thisParms[1].Direction = ParameterDirection.Input;
thisParms[2] = new System.Data.SqlClient.SqlParameter("@where", where);
thisParms[2].Direction = ParameterDirection.Input;
thisParms[3] = new System.Data.SqlClient.SqlParameter("@fieldshow",fieldshow);
thisParms[3].Direction = ParameterDirection.Input;
thisParms[4] = new System.Data.SqlClient.SqlParameter("@fieldorder", fieldorder);
thisParms[4].Direction = ParameterDirection.Input;
thisParms[5] = new System.Data.SqlClient.SqlParameter("@pagecurrent", pagecurrent);
thisParms[5].Direction = ParameterDirection.Input;
thisParms[6] = new System.Data.SqlClient.SqlParameter("@pagesize", pagesize);
thisParms[6].Direction = ParameterDirection.Input;
thisParms[7] = new System.Data.SqlClient.SqlParameter("@pagecount", SqlDbType.Int,32);
thisParms[7].Direction = ParameterDirection.Output;
thisParms[8] = new System.Data.SqlClient.SqlParameter("@itemcount", SqlDbType.Int,32);
thisParms[8].Direction = ParameterDirection.Output;
pagecount = 0;
itemcount = 0;
ErrorMessage = "";
if (SQLCommon.ExecuteStoredProcedure("sp_xt_pagesplit", strConnectionstring, ref thisParms, out ds, out ErrorMessage))
{
pagecount = Convert.ToInt32(thisParms[7].Value.ToString());
itemcount = Convert.ToInt32(thisParms[8].Value.ToString());
return true;
}
return false;
}
public static bool ExecPageQueryMesWork(string tbname, string strConnectionstring, string fieldkey, string where, string fieldshow, string fieldorder, string filedgroup,int pagecurrent, int pagesize, out int pagecount, out int itemcount, out DataTable dt, out string ErrorMessage)
{
DataSet ds;
dt = new DataTable();
SqlParameter[] thisParms = new SqlParameter[9];
thisParms[0] = new System.Data.SqlClient.SqlParameter("@tbname", tbname);
thisParms[1] = new System.Data.SqlClient.SqlParameter("@fieldkey", fieldkey);
thisParms[2] = new System.Data.SqlClient.SqlParameter("@where", where);
thisParms[3] = new System.Data.SqlClient.SqlParameter("@fieldshow", fieldshow);
thisParms[4] = new System.Data.SqlClient.SqlParameter("@fieldOrder", fieldorder);
thisParms[5] = new System.Data.SqlClient.SqlParameter("@PageCurrent", pagecurrent);
thisParms[6] = new System.Data.SqlClient.SqlParameter("@PageSize", pagesize);
thisParms[7] = new System.Data.SqlClient.SqlParameter("@PageCount", SqlDbType.Int, 32);
thisParms[8] = new System.Data.SqlClient.SqlParameter("@ItemCount", SqlDbType.Int, 32);
thisParms[7].Direction = ParameterDirection.Output;
thisParms[8].Direction = ParameterDirection.Output;
pagecount = 0;
itemcount = 0;
ErrorMessage = "";
if (SQLCommon.ExecuteStoredProcedure("sp_xt_pagesplit", strConnectionstring, ref thisParms, out ds, out ErrorMessage))
{
dt = ds.Tables[0];
pagecount = Convert.ToInt32(thisParms[7].Value.ToString());
itemcount = Convert.ToInt32(thisParms[8].Value.ToString());
return true;
}
return false;
}
/// <summary>
/// 根据输入参数,对指定表进行分页显示
/// </summary>
/// <param name="tbname">要进行分页的表/视图的名称</param>
/// <param name="strConnectionstring">表或者视图的主键</param>
/// <param name="fieldkey">表或者视图的主键</param>
/// <param name="where">进行过滤的条件</param>
/// <param name="fieldshow">需要显示的字段名称</param>
/// <param name="fieldorder">排序的条件,直接输入字段名 +desc/asc例如id desc,name asc</param>
/// <param name="filedgroup">排序的条件,直接输入字段名 +desc/asc例如id desc,name asc</param>
/// <param name="pagecurrent">当前页的页码</param>
/// <param name="pagesize">每一页的显示的数据量</param>
/// <param name="pagecount">返回页码总数</param>
/// <param name="itemcount">返回数据总数</param>
/// <param name="ds"></param>
/// <param name="ErrorMessage">返回错误</param>
/// <returns>True / False</returns>
public static bool ExecPageQuery_GroupBy(string tbname, string strConnectionstring, string fieldkey, string where, string fieldshow, string fieldorder,string filedgroup ,int pagecurrent, int pagesize, out int pagecount, out int itemcount, out DataSet ds, out string ErrorMessage)
{
SqlParameter[] thisParms = new SqlParameter[10];
thisParms[0] = new System.Data.SqlClient.SqlParameter("@tbname", tbname);
thisParms[0].Direction = ParameterDirection.Input;
thisParms[1] = new System.Data.SqlClient.SqlParameter("@fieldkey", fieldkey);
thisParms[1].Direction = ParameterDirection.Input;
thisParms[2] = new System.Data.SqlClient.SqlParameter("@where", where);
thisParms[2].Direction = ParameterDirection.Input;
thisParms[3] = new System.Data.SqlClient.SqlParameter("@fieldshow", fieldshow);
thisParms[3].Direction = ParameterDirection.Input;
thisParms[4] = new System.Data.SqlClient.SqlParameter("@fieldorder", fieldorder);
thisParms[4].Direction = ParameterDirection.Input;
thisParms[5] = new System.Data.SqlClient.SqlParameter("@filedgroup", filedgroup);
thisParms[5].Direction = ParameterDirection.Input;
thisParms[6] = new System.Data.SqlClient.SqlParameter("@pagecurrent", pagecurrent);
thisParms[6].Direction = ParameterDirection.Input;
thisParms[7] = new System.Data.SqlClient.SqlParameter("@pagesize", pagesize);
thisParms[7].Direction = ParameterDirection.Input;
thisParms[8] = new System.Data.SqlClient.SqlParameter("@pagecount", SqlDbType.Int, 32);
thisParms[8].Direction = ParameterDirection.Output;
thisParms[9] = new System.Data.SqlClient.SqlParameter("@itemcount", SqlDbType.Int, 32);
thisParms[9].Direction = ParameterDirection.Output;
pagecount = 0;
itemcount = 0;
ErrorMessage = "";
if (SQLCommon.ExecuteStoredProcedure("sp_xt_pagesplit_GroupBy", strConnectionstring, ref thisParms, out ds, out ErrorMessage))
{
pagecount = Convert.ToInt32(thisParms[8].Value.ToString());
itemcount = Convert.ToInt32(thisParms[9].Value.ToString());
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="intGrantee"></param>
/// <param name="intGranteeType"></param>
/// <param name="intObjectId"></param>
/// <param name="intOjbectType"></param>
/// <param name="strConnectionString"></param>
/// <param name="strErrmessage"></param>
/// <returns></returns>
public static bool addGrants(int intGrantee, int intGranteeType, int intObjectId, int intOjbectType,string strConnectionString,out string strErrmessage)
{
string getdate = " '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' ";
string sql = "insert into grants (grantee,granteetype,objectid,objecttype,createtime,creator,creatorid) values("
+intGrantee + ","
+intGranteeType + ","
+intObjectId + ","
+ intOjbectType + ",getdate,'SYSTEM',0)";
if (ExecuteSQL(sql, strConnectionString, out strErrmessage))
{
return true;
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="intGrantee"></param>
/// <param name="intGranteeType"></param>
/// <param name="intObjectId"></param>
/// <param name="intOjbectType"></param>
/// <param name="strConnectionString"></param>
/// <param name="strErrmessage"></param>
/// <returns></returns>
public static bool delGrants(int intGrantee, int intGranteeType, int intObjectId, int intOjbectType, string strConnectionString, out string strErrmessage)
{
string sql = "update grants set deleted=1 where grantee=" + intGrantee + " and granteetype=" + intGranteeType + " and objectid=" + intObjectId + " and objecttype=" + intOjbectType;
if (ExecuteSQL(sql, strConnectionString, out strErrmessage))
{
return true;
}
return false;
}
/// <summary>
/// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="dt">增加数据的数据表</param>
/// <returns></returns>
public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, DataTable dt)
{
string errorMessage;
return SQLCommon.ExecuteStoredProcedure( procedureName, ApplicationConfig.ConnectionString_MES, ref sqlParameters, dt, out errorMessage);
}
/// <summary>
/// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters)
{
string errorMessage;
return SQLCommon.ExecuteStoredProcedure(procedureName, ApplicationConfig.ConnectionString_MES, ref sqlParameters, out errorMessage);
}
/// <summary>
/// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用)
/// </summary>
/// <param name="procedureName"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool ExecuteStoredProcedure(string procedureName, out DataTable dt)
{
string errorMessage;
return SQLCommon.ExecuteStoredProcedure(procedureName, ApplicationConfig.ConnectionString_MES, out dt, out errorMessage);
}
/// <summary>
/// 执行带参数的存储过程
/// </summary>
/// <param name="procedureName"></param>
/// <param name="sqlParameters"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool ExecuteStoredProcedure(string procedureName, ref SqlParameter[] sqlParameters, out DataTable dt)
{
string errorMessage;
DataSet ds;
SQLCommon.ExecuteStoredProcedure(procedureName, ApplicationConfig.ConnectionString_MES, ref sqlParameters,out ds, out errorMessage);
try
{
dt = ds.Tables[0];
return true;
}
catch
{
dt = null;
return false;
}
}
}
}

View File

@@ -0,0 +1,258 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
public class JsonHelper
{
#region
// 序列化
public static string JsonSerializer<T>(T t)
{
// 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
// 使用 WriteObject 方法将 JSON 数据写入到流中。
jsonSerializer.WriteObject(ms, t);
// 流转字符串
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
//替换Json的Date字符串
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
public static T JsonDeserialize<T>(string jsonString)
{
//将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
// 字符串转流
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
// 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T
T obj = (T)jsonSerializer.ReadObject(ms);
return obj;
}
public static string ConvertJsonDateToDateString(Match match)
{
string result = string.Empty;
DateTime dateTime = new DateTime(1970, 1, 1);
dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value));
dateTime = dateTime.ToLocalTime();
result = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
return result;
}
#endregion
// 对象转换为Json
public static string ObjectToJson(object obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue; // 定义JavaScriptSerializer接受字符串的最大长度 hdk 20180524
try
{
return js.Serialize(obj);
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
// 数据表转化为集合
public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
{
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
if (dataRow[dc.ColumnName].GetType() == typeof(DateTime))
{
string str = Convert.ToDateTime(dataRow[dc.ColumnName]).ToString("yyyy-MM-dd HH:mm:ss");
dic.Add(dc.ColumnName, str);
}
else if
(dataRow[dc.ColumnName].GetType() == typeof(byte[]))
{
string str = Convert.ToBase64String((byte[])dataRow[dc.ColumnName]);
dic.Add(dc.ColumnName, str);
}
else
{
dic.Add(dc.ColumnName, dataRow[dc.ColumnName]);
}
//Type type1 = dt.Rows[0]["产品图片"].GetType();
//Type type2 = typeof(byte[]);
}
list.Add(dic);
}
return list;
}
/// <summary>
/// 表转换为Json
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTableToJson(DataTable dt)
{
return ObjectToJson(DataTableToList(dt));
}
/// <summary>
/// 将DataTable中的数据转换成JSON格式
/// </summary>
/// <param name="dt">数据源DataTable</param>
/// <param name="displayCount">是否输出数据总条数</param>
/// <param name="totalcount">JSON中显示的数据总条数</param>
/// <returns></returns>
public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount)
{
StringBuilder JsonString = new StringBuilder();
//Exception Handling
if (dt != null)
{
JsonString.Append("{ ");
JsonString.Append("\"rows\":[ ");
for (int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
//if (dt.Rows[i][j] == DBNull.Value) continue;
if (dt.Columns[j].DataType == typeof(bool))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" +
dt.Rows[i][j].ToString().ToLower() + ",");
}
else if (dt.Columns[j].DataType == typeof(string))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" +
ObjectToJson(dt.Rows[i][j]).ToString() + ",");
//JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
// dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\",");
}
else
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\",");
}
}
else if (j == dt.Columns.Count - 1)
{
//if (dt.Rows[i][j] == DBNull.Value) continue;
if (dt.Columns[j].DataType == typeof(bool))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" +
dt.Rows[i][j].ToString().ToLower());
}
else if (dt.Columns[j].DataType == typeof(string))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" +
ObjectToJson(dt.Rows[i][j]).ToString());
//JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
// dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"");
}
else
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\"");
}
}
}
/*end Of String*/
if (i == dt.Rows.Count - 1)
{
JsonString.Append("} ");
}
else
{
JsonString.Append("}, ");
}
}
JsonString.Append("]");
if (displayCount)
{
JsonString.Append(",");
JsonString.Append("\"total\":");
JsonString.Append(totalcount);
}
JsonString.Append("}");
return JsonString.ToString().Replace("\n", "");
}
else
{
return null;
}
}
StringBuilder result = new StringBuilder();
StringBuilder sb = new StringBuilder();
/// <summary>
/// 根据DataTable生成EasyUI Tree Json树结构
/// </summary>
/// <param name="tabel">数据源</param>
/// <param name="idCol">ID列</param>
/// <param name="txtCol">Text列</param>
/// <param name="url">节点Url</param>
/// <param name="rela">关系字段</param>
/// <param name="pId">父ID</param>
public string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId)
{
result.Append(sb.ToString());
sb.Clear();
if (tabel.Rows.Count > 0)
{
sb.Append("[");
string filer = string.Format("{0}='{1}'", rela, pId);
DataRow[] rows = tabel.Select(filer);
if (rows.Length > 0)
{
foreach (DataRow row in rows)
{
sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\"");
if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
{
sb.Append(",\"children\":");
GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]);
result.Append(sb.ToString());
sb.Clear();
}
result.Append(sb.ToString());
sb.Clear();
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
result.Append(sb.ToString());
sb.Clear();
}
return result.ToString();
}
}

View File

@@ -0,0 +1,959 @@
using System;
//using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Specialized;
//using System.Data.OleDb;
using SystemFramework;
using BasicData;
namespace BizDataAccess
{
/// <summary>
/// 数据访问类——提供通用的数据访问方法
/// </summary>
public partial class SQLCommon
{
/// <summary>
///
/// </summary>
/// <param name="json"></param>
/// <param name="thisParms"></param>
/// <param name="isOutput"></param>
/// <returns></returns>
public static bool GetCmdParam(jsonobj json, ref SqlParameter[] thisParms,out bool isOutput )
{
//SqlParameter[] thisParms=null;
string[] parmas;
isOutput = false;
try
{
parmas = json.Param.Split('&');
// 判断输入字符串是否合法,若不合法,则移除该条件参数
for (int i = parmas.Length-1; i >= 0; i--) {
string a = parmas[i];
string illegal1 = "==";
string illegal2 = "null";
string illegal3 = "undefined";
if (a.IndexOf(illegal1) > -1 || a.IndexOf(illegal2) > -1 || a.IndexOf(illegal3) > -1) {
ArrayList ar = new ArrayList(parmas);
ar.Remove(parmas[i]);
parmas = (string[])ar.ToArray(typeof(string));
}
}
// 移除不合法参数后重新定义thisParms长度
thisParms = new SqlParameter[parmas.Length];
for (int i = 0; i < parmas.Length; i++)
{
string[] pp = parmas[i].Split('=');
object inputValue = null;
if (pp.Length == 4)
{
if(pp[3]=="output")
{
inputValue = GetInputValue(pp);
thisParms[i] = new SqlParameter(pp[0], inputValue);
thisParms[i].Direction = ParameterDirection.Output;
isOutput = true;
}
}
else if (pp.Length == 3)
{
inputValue = GetInputValue(pp);
thisParms[i] = new SqlParameter(pp[0], inputValue);
}
else if (pp.Length == 2)
{
thisParms[i] = new SqlParameter(pp[0], pp[1]);
}
}
}
catch (Exception ex)
{
ex.ToString();
return false;
}
return true;
}
/// <summary>
/// 根据输出参数获得输出变量Json字符串
/// </summary>
/// <param name="thisParms"></param>
/// <returns></returns>
public static string GetOutputValue(SqlParameter[] thisParms)
{
string resultOutput = "";
//[{"name1":"value1","name2":"value2"}]
resultOutput = "";
int outputCount=0;
for (int i = 0; i < thisParms.Length; i++)
{
if (thisParms[i].Direction == ParameterDirection.Output)
{
if (outputCount == 0)
{
resultOutput = resultOutput + "\"" + thisParms[i].ParameterName + "\":" + "\"" + thisParms[i].Value.ToString() + "\"";
}
else
{
resultOutput = resultOutput + "," + "\"" + thisParms[i].ParameterName + "\":" + "\"" + thisParms[i].Value.ToString() + "\"";
}
outputCount++;
}
}
resultOutput = "[{" + resultOutput + "}]";
return resultOutput;
}
/// <summary>
/// 发动机型号代码&1&Int|工位号&ML050&String|PageCurrent&1&Int|PageSize&10&Int|PageCount&0&Int&Output|ItemCount&0&Int&Output
/// </summary>
/// <param name="pp"></param>
/// <returns></returns>
static object GetInputValue(string[] pp)
{
object inputValue = null;
switch (pp[2])
{
case "int":
inputValue = Convert.ToInt32(pp[1]);
break;
case "string":
inputValue = pp[1];
break;
case "boolean":
if(pp[1]=="1")
{
inputValue = true;
}
else
{
inputValue = false;
}
break;
case "datetime":
inputValue = Convert.ToDateTime(pp[1]);
break;
default:
inputValue = pp[1];
break;
}
return inputValue;
}
/// <summary>
/// SqlServer连接状态
/// =true 连接正常
/// =false 连接失败
/// </summary>
static bool sqlServerConnectionStatus=true;
/// <summary>
/// SqlServer连接状态
/// =true 连接正常
/// =false 连接失败
/// </summary>
public static bool SqlServerConnectionStatus
{
get
{
return sqlServerConnectionStatus;
}
set
{
sqlServerConnectionStatus = value;
}
}
/// <summary>
/// 测试与数据的连接
/// SqlServer连接状态
/// =true 连接正常
/// =false 连接失败
/// </summary>
/// <returns></returns>
public static void TestConnection()
{
string sql = "select top 1 uid from sysusers ";
string connectionString = ApplicationConfig.ConnectionString_MES;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.ExecuteNonQuery();
SqlServerConnectionStatus = true;
return;
}
catch (Exception e)
{
//SqlServerConnectionStatus = false;
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
// SqlServer 与数据通讯状态
return;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
/// <summary>
/// 测试与数据的连接
/// SqlServer连接状态
/// =true 连接正常
/// =false 连接失败
/// </summary>
/// <returns></returns>
public static bool TestConnectionWorkStart()
{
bool isOK = true;
string sql = "select top 1 uid from sysusers ";
string connectionString = ApplicationConfig.ConnectionString_MES;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.ExecuteNonQuery();
return isOK;
}
catch
{
isOK = false;
return isOK;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
/// <summary>
/// 执行标准SQL语句不要求返回结果适合增、删、改
/// </summary>
/// <param name="sql">标准SQL语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteNonQuery(StringCollection sql, string connectionString, out string errorMessage)
{
bool result = false;
errorMessage = "";
string sqlText="";
//SqlCommand cmd;
// using (SqlConnection connection =
//new SqlConnection(GetConnectionString()))
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
for (int i = 0; i < sql.Count; i++)
{
cmd.CommandText = sql[i].ToString();
sqlText = cmd.CommandText;
//SqlCommand cmd = new SqlCommand(sql[i].ToString(), conn);
cmd.ExecuteNonQuery();
}
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sqlText + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
return result;
}
//try
//{
// if (!SqlServerConnectionStatus) return false;
// conn.Open();
// cmd = new SqlCommand();
// cmd.Connection = conn;
// for (int i = 0; i < sql.Count; i++)
// {
// cmd.CommandText = sql[i].ToString();
// sqlText = cmd.CommandText;
// //SqlCommand cmd = new SqlCommand(sql[i].ToString(), conn);
// cmd.ExecuteNonQuery();
// }
// SqlServerConnectionStatus = true;
// result = true;
//}
//catch (Exception e)
//{
// errorMessage = e.ToString();
// TestConnection();
// ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sqlText + "\r\n连接字符串\r\n" + connectionString);
//}
//finally
//{
// if (conn.State == ConnectionState.Open)
// conn.Close();
//}
//return result;
}
/// <summary>
/// 执行SQL命令实现Insert Update Delete 命令
/// </summary>
/// <param name="sql"></param>
/// <param name="connectionString"></param>
/// <param name="errorMessage"></param>
/// <returns></returns>
public static bool ExecuteNonQuery(string sql, string connectionString, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
cmd.ExecuteNonQuery();
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 执行SQL后返回第一行第一列的结果
/// </summary>
/// <param name="sql"></param>
/// <param name="connectionString"></param>
/// <param name="count"></param>
/// <param name="errorMessage"></param>
/// <returns></returns>
public static bool ExecuteOutNum(string sql, string connectionString, out int count, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (SqlConnection conn = new SqlConnection(connectionString))
{
count = 0;
try
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
count = Convert.ToInt32(cmd.ExecuteScalar().ToString());
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="ds">查询结果记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataset(string sql, string connectionString, out DataSet ds, out string errorMessage)
{
bool result = false;
errorMessage = "";
ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.SelectCommand = new SqlCommand(sql, conn);
dsCommand.Fill(ds);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="dt">查询结果记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataTable(string sql, string connectionString, out DataTable dt, out string errorMessage)
{
bool result = false;
errorMessage = "";
dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.SelectCommand = new SqlCommand(sql, conn);
dsCommand.Fill(dt);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 执行标准SQL查询语句返回记录集
/// </summary>
/// <param name="sql">标准SQL查询语句</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="dr">查询结果记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteDataReader(string sql, string connectionString, out SqlDataReader dr, out string errorMessage)
{
bool result = false;
errorMessage = "";
dr = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
if (!SqlServerConnectionStatus) return false;
conn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteNonQuery\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(需要返回查询的记录集的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="ds">存储过程里面返回的记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, string connectionString, ref SqlParameter[] sqlParameters, out DataSet ds, out string errorMessage)
{
bool result = false;
errorMessage = "";
ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.SelectCommand = new SqlCommand(procedureName, conn);
dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
dsCommand.SelectCommand.CommandTimeout = 0;
if (sqlParameters != null)
{
for (int i = 0; i < sqlParameters.Length; i++)
{
dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]);
}
}
dsCommand.Fill(ds);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(需要返回查询的记录集的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="startRecord">从其开始的从零开始的记录号</param>
/// <param name="maxRecords">要检索的最大记录数</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="ds">存储过程里面返回的记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, string connectionString, int startRecord, int maxRecords, ref SqlParameter[] sqlParameters, out DataSet ds, out string errorMessage)
{
bool result = false;
errorMessage = "";
ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.SelectCommand = new SqlCommand(procedureName, conn);
dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
if(sqlParameters!=null)
{
for (int i = 0; i < sqlParameters.Length; i++)
{
dsCommand.SelectCommand.Parameters.Add(sqlParameters[i]);
}
}
dsCommand.Fill(ds, startRecord, maxRecords, "srcTable");
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(不需要返回查询的记录集的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, string connectionString, ref SqlParameter[] sqlParameters, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlCommand cmd = new SqlCommand(procedureName, conn))
{
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
if(sqlParameters!=null)
{
for (int i = 0; i < sqlParameters.Length; i++)
{
cmd.Parameters.Add(sqlParameters[i]);
}
}
cmd.ExecuteNonQuery();
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(需要返回查询的记录集的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
///
/// <param name="ds">存储过程里面返回的记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, string connectionString, out DataSet ds, out string errorMessage)
{
bool result = false;
errorMessage = "";
ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.SelectCommand = new SqlCommand(procedureName, conn);
dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
dsCommand.Fill(ds);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(需要返回查询的记录集的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
///
/// <param name="dt">存储过程里面返回的记录集</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, string connectionString, out DataTable dt, out string errorMessage)
{
bool result = false;
errorMessage = "";
dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.SelectCommand = new SqlCommand(procedureName, conn);
dsCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
dsCommand.Fill(dt);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 以表的形式增加数据到数据库
/// </summary>
/// <param name="sql"></param>
/// <param name="sqlParameters"></param>
/// <param name="connectionString"></param>
/// <param name="dt"></param>
/// <param name="errorMessage"></param>
/// <returns></returns>
public static bool ExecuteSQL(string sql, ref SqlParameter[] sqlParameters, string connectionString, DataTable dt, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.InsertCommand = new SqlCommand(sql, conn);
for (int i = 0; i < sqlParameters.Length; i++)
{
sqlParameters[i].IsNullable = true;
dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]);
}
if (dt == null) return false;
dt.AcceptChanges();
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i].SetAdded();
}
dsCommand.Update(dt);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
//ApplicationConfig.ConnectionStringPIS_NEW_Value = "0";
TestConnection();
errorMessage = e.ToString();
ApplicationLog.WriteLog(e, "\r\nExecuteSQL\r\nSQL语句\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(增加数据的数据表的到数据库的调用)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="dt">增加数据的数据表</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure(string procedureName, string connectionString, ref SqlParameter[] sqlParameters, DataTable dt, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
if (!SqlServerConnectionStatus) return false;
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.InsertCommand = new SqlCommand(procedureName, conn);
dsCommand.InsertCommand.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < sqlParameters.Length; i++)
{
dsCommand.InsertCommand.Parameters.Add(sqlParameters[i]);
}
if (dt == null) return false;
dt.AcceptChanges();
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i].SetAdded();
}
dsCommand.Update(dt);
}
SqlServerConnectionStatus = true;
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 提供通用的调用存储过程的方法(更新数据)
/// </summary>
/// <param name="procedureName">存储过程名称</param>
/// <param name="connectionString">连库字符串</param>
/// <param name="sqlParameters">存储过程参数数组</param>
/// <param name="dt">增加数据的数据表</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>布尔值true表示该执行成功false表示执行失败</returns>
public static bool ExecuteStoredProcedure_Update(string procedureName, string connectionString, ref SqlParameter[] sqlParameters, DataTable dt, out string errorMessage)
{
bool result = false;
errorMessage = "";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
using (SqlDataAdapter dsCommand = new SqlDataAdapter())
{
dsCommand.UpdateCommand = new SqlCommand(procedureName, conn);
dsCommand.UpdateCommand.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < sqlParameters.Length; i++)
{
dsCommand.UpdateCommand.Parameters.Add(sqlParameters[i]);
}
if (dt == null) return false;
dt.AcceptChanges();
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i].SetAdded();
}
dsCommand.Update(dt);
}
result = true;
}
catch (Exception e)
{
errorMessage = e.ToString();
TestConnection();
ApplicationLog.WriteLog(e, "\r\nExecuteStoredProcedure\r\n存储过程\r\n" + procedureName + "\r\n连接字符串\r\n" + connectionString);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
return result;
}
/// <summary>
/// 增加记录后,返回自动编号
/// </summary>
/// <param name="sql"></param>
/// <param name="newID"></param>
/// <returns></returns>
public static bool ExecuteNonQuery_newID(string sql, out long newID)
{
sql += ";select @@identity";
string connectionString;
connectionString = ApplicationConfig.ConnectionString_MES;
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
newID = Convert.ToInt64(cmd.ExecuteScalar());
}
return true;
}
catch (Exception e)
{
newID = 0;
TestConnection();
ApplicationLog.WriteLog(e, "\r\n ExecuteNonQuery_newID\r\n存储过程\r\n" + sql + "\r\n连接字符串\r\n" + connectionString);
return false;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
}
}
}