当前位置:网站首页>Entity framework extends the actual combat, small project reconfiguration, no trouble
Entity framework extends the actual combat, small project reconfiguration, no trouble
2022-06-13 02:49:00 【afeng124】
A console program ,MSSQL 2008 database , One of the large table data exceeds 6000 Ten million , Development time is limited, it is impossible to spend a lot of time designing 、 framework . The first reason to use the console is to achieve efficient operation , Second, the program runs regularly on the server without human intervention . To ensure the maintainability and rapid development of the program and the efficient operation of the program , There is no time for layered development , Directly used entity framework And combine ado.net Yes EF It has been extended . Do not toss because of fear EF There is a performance problem using sqlbuckcopy Bulk insert data , Use DB FIRST. Refactoring is because it turns out to be oracle database , Database has been changed to MSSQL 2008.
1、 Solution 、 framework
Solution :



2、 Business description
The main business of the program is to read the... Under the specified directory XML file , Sort and piece up the records in the files to form the corresponding table in the database datatable, And then use SqlBulkCopy Bulk insert database . The file is from a remote computer through FTP The uploaded .XML The records inside are inconsistent with the table structure of the corresponding table in the database to be stored , Need conversion and completion . The program runs regularly , Use the scheduled task of the operating system to schedule . The log component uses log4net, To achieve console display and database logging .
3、 Key codes and coding ideas
1、 Business logic implementation

2、EF The extension class
using System.Data;
using System.Data.EntityClient;
using System;
using System.Data.SqlClient;
using System.Configuration;
namespace XXX_App
{
public partial class XXX_DBEntities : global::System.Data.Objects.ObjectContext
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
/// <summary>
/// Use ado.net perform sqlbulkcopy
/// </summary>
/// <param name="dt"></param>
/// <param name="efConnectStr">webconfig Database connection string in </param>
/// <returns></returns>
public bool ExecuteSqlBulkCopy(DataTable dt)
{
string dbConnStr = this.GetEF_ConnectStr2Ado_ConnectStr();
bool result = false;
#region ado.net execute sqlbulkcopy
using (SqlConnection dbConn = new SqlConnection(dbConnStr))
{
try
{
#region perform sqlbulkcopy
dbConn.Open();
SqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "delete sc_productsource_temp";
cmd.ExecuteNonQuery();
new SqlBulkCopy(dbConn)
{
DestinationTableName = "sc_productsource_temp",
BatchSize = dt.Rows.Count,
BulkCopyTimeout = 1800
}.WriteToServer(dt);
#endregion
result = true;
}
catch (Exception ex)
{
result = false;
throw new Exception(ex.Message);
}
finally
{
if (result)
{
#region The flow detail record of the temporary table is transferred to the official SC_PRODUCTSOURCE
SqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = " INSERT INTO SC_PRODUCTSOURCE (PRODUCTSOURCEID,FACTORYID,PRDLINEID "+
" ,MACRANDOMCODE ,PRODUCTBATCHIDX ,LASERDNA_CODE ,PRODUCTNO ,PRODUCTNAME,PRODUCTTYPENAME"+
" ,PRODUCTDATE ,PRINTCODEDT ,FACTORYSHIFTNO ,OUTBOX_DNACODE ,VIRTUALBALECODE" +
" ,SENDTONDC_DT,FAC_NO,PRODUCTVERSION) " +
" SELECT NEWID() PRODUCTSOURCEID,FACTORYID,PRDLINEID,MACRANDOMCODE,PRODUCTBATCHIDX " +
" ,LASERDNA_CODE,PRODUCTNO,PRODUCTNAME,PRODUCTTYPENAME,PRODUCTDATE,PRINTCODEDT " +
" ,FACTORYSHIFTNO,OUTBOX_DNACODE,VIRTUALBALECODE,SENDTONDC_DT,FAC_NO,PRODUCTVERSION " +
" FROM sc_productsource_temp";
cmd.ExecuteNonQuery();
#endregion
}
dbConn.Close();
}
}
#endregion
return result;
}
/// <summary>
/// Prepare a temporary table
/// </summary>
/// <param name="efConnectStr"></param>
/// <returns></returns>
public DataTable GetTmpNewDataTable()
{
return this.GetDbHelperSQL_Instance().Query("select * from sc_productsource_temp where 1=2").Tables[0];
}
/// <summary>
/// take EF The connection string of is converted to Ado.net Connection string of
/// </summary>
/// <param name="efConnectStr"></param>
/// <returns></returns>
private string GetEF_ConnectStr2Ado_ConnectStr()
{
string[] tmpStr = config.ConnectionStrings.ConnectionStrings["XXX_DBEntities"].ConnectionString.Split(";".ToCharArray());
string dbConnStr = string.Empty;
if (tmpStr.Length == 8)
{
// Splice new and usable ado.net Connection string
dbConnStr = string.Join(";", new string[] { "Data Source =" + base.Connection.DataSource, tmpStr[3], tmpStr[4], tmpStr[5], tmpStr[6].TrimEnd(new char[] { '"' }) });
return dbConnStr;
}
else
{
return string.Empty;
throw new Exception(" Please configure the database connection mode as :sql authentication ; I won't support it WinNT Integrated security approach .");
}
}
/// <summary>
/// Get the data of the first row and the first column
/// </summary>
/// <param name="efConnectStr"></param>
/// <param name="sqlTxt"></param>
/// <returns></returns>
public string AdoExecuteScalar(string sqlTxt)
{
string dbConnStr = this.GetEF_ConnectStr2Ado_ConnectStr();
using (DbHelperSQL db = new DbHelperSQL(dbConnStr))
{
return db.GetSingle(sqlTxt).ToString();
}
}
public DbHelperSQL GetDbHelperSQL_Instance()
{
string dbConnStr = this.GetEF_ConnectStr2Ado_ConnectStr();
return new DbHelperSQL(dbConnStr);
}
}
}
3、 Modified dynamic software DbHelper,Ado.net Storage class
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;
namespace XXX_App
{
/// <summary>
/// Data access Abstract basic class
/// Copyright (C) Maticsoft
/// </summary>
public class DbHelperSQL : IDisposable
{
// Database connection string (web.config To configure the ), Multiple databases available DbHelperSQLP To achieve .
private string connectionString;
/// <summary>
/// Database connection string
/// </summary>
public string ConnectionString
{
get { return connectionString; }
}
public DbHelperSQL(string connStr)
{
connectionString = connStr;
}
#region Common method
/// <summary>
/// Determine whether there is a field in a table
/// </summary>
/// <param name="tableName"> The name of the table </param>
/// <param name="columnName"> Column name </param>
/// <returns> Whether there is </returns>
public bool ColumnExists(string tableName, string columnName)
{
string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
object res = GetSingle(sql);
if (res == null)
{
return false;
}
return Convert.ToInt32(res) > 0;
}
public 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 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()); // Or maybe =0
}
if (cmdresult == 0)
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Does the table exist
/// </summary>
/// <param name="TableName"></param>
/// <returns></returns>
public bool TabExists(string TableName)
{
string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
//string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')";
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 bool Exists(string strSql, params SqlParameter[] 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 Easy to implement SQL sentence
/// <summary>
/// perform SQL sentence , Returns the number of records affected
/// </summary>
/// <param name="SQLString">SQL sentence </param>
/// <returns> Number of records affected </returns>
public int ExecuteSql(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
public int ExecuteSqlByTime(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// Execute more than one SQL sentence , Implement database transactions .
/// </summary>
/// <param name="SQLStringList"> multiple SQL sentence </param>
public int ExecuteSqlTran(List<String> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
SqlTransaction tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
int count = 0;
for (int n = 0; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > 1)
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return 0;
}
}
}
/// <summary>
/// Execute with a stored procedure parameter SQL sentence .
/// </summary>
/// <param name="SQLString">SQL sentence </param>
/// <param name="content"> Parameter contents , For example, a field is a complex format article , There are special symbols , You can add... In this way </param>
/// <returns> Number of records affected </returns>
public int ExecuteSql(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// Execute with a stored procedure parameter SQL sentence .
/// </summary>
/// <param name="SQLString">SQL sentence </param>
/// <param name="content"> Parameter contents , For example, a field is a complex format article , There are special symbols , You can add... In this way </param>
/// <returns> Number of records affected </returns>
public object ExecuteSqlGet(string SQLString, string content)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(SQLString, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText);
myParameter.Value = content;
cmd.Parameters.Add(myParameter);
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.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// Insert an image format field into the database ( Another example similar to the above )
/// </summary>
/// <param name="strSQL">SQL sentence </param>
/// <param name="fs"> Image byte , The field type of the database is image The situation of </param>
/// <returns> Number of records affected </returns>
public int ExecuteSqlInsertImg(string strSQL, byte[] fs)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(strSQL, connection);
System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image);
myParameter.Value = fs;
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
/// <summary>
/// Execute a statement that evaluates the results of a query , Return query results (object).
/// </summary>
/// <param name="SQLString"> Compute query result statement </param>
/// <returns> Query results (object)</returns>
public object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(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.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
public object GetSingle(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// Execute query statement , return SqlDataReader ( Be careful : After calling this method , Be sure to be right SqlDataReader Conduct Close )
/// </summary>
/// <param name="strSQL"> Query statement </param>
/// <returns>SqlDataReader</returns>
public SqlDataReader ExecuteReader(string strSQL)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(strSQL, connection);
try
{
connection.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
/// <summary>
/// Execute query statement , return DataSet
/// </summary>
/// <param name="SQLString"> Query statement </param>
/// <returns>DataSet</returns>
public DataSet Query(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
public DataSet Query(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.SelectCommand.CommandTimeout = Times;
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
#endregion
#region Execute... With parameters SQL sentence
/// <summary>
/// perform SQL sentence , Returns the number of records affected
/// </summary>
/// <param name="SQLString">SQL sentence </param>
/// <returns> Number of records affected </returns>
public int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// Execute more than one SQL sentence , Implement database transactions .
/// </summary>
/// <param name="SQLStringList">SQL Hash table of statement (key by sql sentence ,value Is the statement of SqlParameter[])</param>
public void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
// loop
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// Execute more than one SQL sentence , Implement database transactions .
/// </summary>
/// <param name="SQLStringList">SQL Hash table of statement (key by sql sentence ,value Is the statement of SqlParameter[])</param>
public int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
int count = 0;
// loop
foreach (CommandInfo myDE in cmdList)
{
string cmdText = myDE.CommandText;
SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
{
if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
{
trans.Rollback();
return 0;
}
object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > 0;
if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
{
trans.Rollback();
return 0;
}
if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
{
trans.Rollback();
return 0;
}
continue;
}
int val = cmd.ExecuteNonQuery();
count += val;
if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
{
trans.Rollback();
return 0;
}
cmd.Parameters.Clear();
}
trans.Commit();
return count;
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// Execute more than one SQL sentence , Implement database transactions .
/// </summary>
/// <param name="SQLStringList">SQL Hash table of statement (key by sql sentence ,value Is the statement of SqlParameter[])</param>
public void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
int indentity = 0;
// loop
foreach (CommandInfo myDE in SQLStringList)
{
string cmdText = myDE.CommandText;
SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters;
foreach (SqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (SqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// Execute more than one SQL sentence , Implement database transactions .
/// </summary>
/// <param name="SQLStringList">SQL Hash table of statement (key by sql sentence ,value Is the statement of SqlParameter[])</param>
public void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
int indentity = 0;
// loop
foreach (DictionaryEntry myDE in SQLStringList)
{
string cmdText = myDE.Key.ToString();
SqlParameter[] cmdParms = (SqlParameter[])myDE.Value;
foreach (SqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (SqlParameter q in cmdParms)
{
if (q.Direction == ParameterDirection.Output)
{
indentity = Convert.ToInt32(q.Value);
}
}
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
/// <summary>
/// Execute a statement that evaluates the results of a query , Return query results (object).
/// </summary>
/// <param name="SQLString"> Compute query result statement </param>
/// <returns> Query results (object)</returns>
public object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
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.SqlClient.SqlException e)
{
throw e;
}
}
}
}
/// <summary>
/// Execute query statement , return SqlDataReader ( Be careful : After calling this method , Be sure to be right SqlDataReader Conduct Close )
/// </summary>
/// <param name="strSQL"> Query statement </param>
/// <returns>SqlDataReader</returns>
public SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (System.Data.SqlClient.SqlException e)
{
throw e;
}
}
/// <summary>
/// Execute query statement , return DataSet
/// </summary>
/// <param name="SQLString"> Query statement </param>
/// <returns>DataSet</returns>
public DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
}
private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] 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 (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
#endregion
#region Stored procedure operations
/// <summary>
/// Execute stored procedures , return SqlDataReader ( Be careful : After calling this method , Be sure to be right SqlDataReader Conduct Close )
/// </summary>
/// <param name="storedProcName"> Stored procedure name </param>
/// <param name="parameters"> Stored procedure parameters </param>
/// <returns>SqlDataReader</returns>
public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlDataReader returnReader;
connection.Open();
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.CommandType = CommandType.StoredProcedure;
returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
return returnReader;
}
/// <summary>
/// Execute stored procedures
/// </summary>
/// <param name="storedProcName"> Stored procedure name </param>
/// <param name="parameters"> Stored procedure parameters </param>
/// <param name="tableName">DataSet Table name in result </param>
/// <returns>DataSet</returns>
public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet dataSet = new DataSet();
connection.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
sqlDA.SelectCommand.CommandTimeout = Times;
sqlDA.Fill(dataSet, tableName);
connection.Close();
return dataSet;
}
}
/// <summary>
/// structure SqlCommand object ( Used to return a result set , Instead of an integer value )
/// </summary>
/// <param name="connection"> Database connection </param>
/// <param name="storedProcName"> Stored procedure name </param>
/// <param name="parameters"> Stored procedure parameters </param>
/// <returns>SqlCommand</returns>
private SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection);
command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
if (parameter != null)
{
// Check the output parameters of unassigned values , Allocate it to DBNull.Value.
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
return command;
}
/// <summary>
/// Execute stored procedures , Returns the number of rows affected
/// </summary>
/// <param name="storedProcName"> Stored procedure name </param>
/// <param name="parameters"> Stored procedure parameters </param>
/// <param name="rowsAffected"> Number of rows affected </param>
/// <returns></returns>
public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
int result;
connection.Open();
SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
rowsAffected = command.ExecuteNonQuery();
result = (int)command.Parameters["ReturnValue"].Value;
return result;
}
}
/// <summary>
/// establish SqlCommand Object instances ( Used to return an integer value )
/// </summary>
/// <param name="storedProcName"> Stored procedure name </param>
/// <param name="parameters"> Stored procedure parameters </param>
/// <returns>SqlCommand Object instances </returns>
private SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, 4, ParameterDirection.ReturnValue,
false, 0, 0, string.Empty, DataRowVersion.Default, null));
return command;
}
#endregion
#region IDisposable member
public void Dispose()
{
connectionString = string.Empty;
}
#endregion
}
}
4、EF And the use of extension classes
/// <summary>
/// Parse into database
/// </summary>
/// <param name="ds"></param>
/// <param name="factoryNo"></param>
/// <param name="db"></param>
public static void XmlFile2DataBase(ref DataSet ds, string factoryNo, XXX_DBEntities db)
{
var dtProductLine = ds.Tables["line"];
var dtLinkData = ds.Tables["bc"];
// There have been xml Missing fields ,84K The size of zip In the bag xml bc Table only 3 A field , No batch number and date . If it is this file, skip .
if (dtLinkData.Columns.Count != 5)
return;
string outBoxNo = dtLinkData.Rows[0]["out"].ToString();
// Check for duplicate records , If there is one, ignore , As long as there is a box code repetition in this file , It indicates that this file is uploaded repeatedly . Transaction control to file .
decimal cnt = decimal.Parse(db.AdoExecuteScalar(string.Format("select count(*) as cnt from SC_PRODUCTSOURCE s where s.outbox_dnacode = '{0}'", outBoxNo)).ToString());
if (cnt > 0)
{
return;
}
var dt = db.GetTmpNewDataTable();
#region Prepare temporary data , And use OracleBulkCopy Batch insert , Once per production line
foreach (DataRow dr in dtProductLine.Rows)
{
if (!string.IsNullOrEmpty(dr["pid"].ToString()))
{
dt.Rows.Clear();
int prdCode = int.Parse(dr["psid"].ToString());
var product = db.ProductInfo.Where(p => p.PRODUCT_CODE == prdCode).FirstOrDefault();
string prdName = product.PRODUCT_CNNAME;
string prdBrandName = product.PRD_BRAND;
DataView dv = dtLinkData.DefaultView;
dv.RowFilter = string.Format("data_Id={0}", dr["line_Id"].ToString());
foreach (DataRowView itemRow in dv)
{
string[] itemList = itemRow["bc_Text"].ToString().Split(",".ToCharArray());
string batchNo = itemRow["batchno"].ToString();
string outBoxNoSub = itemRow["out"].ToString();
for (int idx = 0; idx < itemList.Length; idx++)
{
DateTime dtProduct = new DateTime(1901, 01, 01);
DateTime.TryParse(itemRow["maketime"].ToString(), out dtProduct);
var drProductLinkData = dt.NewRow();
#region A box of production data
drProductLinkData["PRODUCTSOURCEID"] = Guid.NewGuid().ToString("N").ToUpper();
drProductLinkData["FACTORYID"] = factoryNo;
drProductLinkData["PRDLINEID"] = dr["no"].ToString();
drProductLinkData["MACRANDOMCODE"] = itemList[idx];
drProductLinkData["PRODUCTBATCHIDX"] = batchNo;
drProductLinkData["LASERDNA_CODE"] = "";
drProductLinkData["PRODUCTNO"] = int.Parse(dr["psid"].ToString());
drProductLinkData["PRODUCTNAME"] = prdName;
drProductLinkData["PRODUCTTYPENAME"] = prdBrandName;
drProductLinkData["PRODUCTDATE"] = dtProduct;
drProductLinkData["PRINTCODEDT"] = dtProduct;
drProductLinkData["FACTORYSHIFTNO"] = "";
drProductLinkData["OUTBOX_DNACODE"] = outBoxNoSub;
drProductLinkData["VIRTUALBALECODE"] = "";
drProductLinkData["SENDTONDC_DT"] = DateTime.Now;
drProductLinkData["FAC_NO"] = factoryNo;
drProductLinkData["PRODUCTVERSION"] = DateTime.Now;
#endregion
dt.Rows.Add(drProductLinkData);
}
}
if (dt.Rows.Count > 0)
{
db.ExecuteSqlBulkCopy(dt);
}
}
}
#endregion
}
4、 Program running effect and screenshot
1、 journal

2、 Screenshot
no , Because the program is too efficient , There are no files to parse for a while . ha-ha
Conclusion : You don't need a fixed mindset to do a project , For example, we must have a layered architecture , It must be something X Technology , Must be highly scalable 、 High reusability . Small projects , Fast 、 Stable 、 Efficiency and maintainability are the key points to be considered . Martial arts in the world , Fast break not only . ha-ha ...
PS:CSS The style is the garden friend's , I didn't write the style in the blog settings , Is on the page HTML Add custom styles in mode .
边栏推荐
- Android lightweight cache processing
- Linked list: reverse linked list
- Principle and steps of principal component analysis (PCA)
- [data analysis and visualization] key points of data drawing 12- importance of chart notes
- Special topic I of mathematical physics of the sprint strong foundation program
- MySQL index
- HEAP[xxx.exe]: Invalid address specified to RtlValidateHeap( 0xxxxxx, 0x000xx)
- Linked list: delete the penultimate node of the linked list
- How can intelligent safe power distribution devices reduce the occurrence of electrical fire accidents?
- Retrofit easy to use
猜你喜欢
![Leetcode 473. Match to square [violence + pruning]](/img/3a/975b91dd785e341c561804175b6439.png)
Leetcode 473. Match to square [violence + pruning]

Opencvshare4 and vs2019 configuration

Bi modal progressive mask attention for fine graded recognition

03 认识第一个view组件
![[data analysis and visualization] key points of data drawing 5- the problem of error line](/img/d7/a54129d2c7bdf7caf764f6f8db9fc1.jpg)
[data analysis and visualization] key points of data drawing 5- the problem of error line
![[reading papers] comparison of deeplobv1-v3 series, brief review](/img/80/714b8e5b2ad31b0a1a0b8320a3c714.jpg)
[reading papers] comparison of deeplobv1-v3 series, brief review

Pycharm installation pyqt5 and its tools (QT designer, pyuic, pyrcc) detailed tutorial

Linked lists: rearranging linked lists

02 optimize the default structure of wechat developer tools

Prometheus install and register services
随机推荐
[common tools] pyautogui tutorial
数仓笔记|针对客户维度建模需要关注的5个因素
[data analysis and visualization] key points of data drawing 8- use of circular bar chart
Detailed explanation of UCI datasets and their data processing (with 148 datasets and processing codes attached)
遍历数组,删除某元素,直到删除为止
Vant框架中关于IndexBar索引栏的CDN单页面引用,无法正常展示
OneNote User Guide (1)
Use of OpenCV 12 findcircuits and drawcircuits
Multiple knapsack problem
CDN single page reference of indexbar index column in vant framework cannot be displayed normally
OpenCVSharpSample04WinForms
Ijkplayer source code - audio playback
Opencv 10 brightness contrast adjustment
Opencv 15 face recognition and eye recognition
Data warehouse notes | 5 factors that need attention for customer dimension modeling
Pycharm installation pyqt5 and its tools (QT designer, pyuic, pyrcc) detailed tutorial
wx. Createselectorquery() gets the usage of DOM nodes in components
Use of OpenCV 11 kmeans clustering
Ijkplayer source code - setting options
Linked list: orderly circular linked list