使用entitiy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient; namespace SQL
{
public class DBParse
{
/// <summary>
/// 獲取DB中所有的表格
/// </summary>
/// <returns></returns>
public List<TableEntity> GetAllTable()
{
string sql = "SELECT Name FROM SysObjects Where XType='U' ORDER BY Name";
DataTable dt = DbHelperSQL.Query(sql).Tables[];
List<TableEntity> list = new List<TableEntity>();
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow dr in dt.Rows)
{
TableEntity entity = new TableEntity() { TableName = dr["Name"].ToString() };
list.Add(entity);
}
} return list;
} public List<TableInfoEntity> GetTableInfo(string tablename)
{
string strProc = "sp_columns";
SqlParameter[] parameters = {
new SqlParameter("@table_name", SqlDbType.VarChar,)
};
parameters[].Value = tablename;
DataTable dt = DbHelperSQL.RunProcedure(strProc,parameters,tablename).Tables[];
List<TableInfoEntity> list = new List<TableInfoEntity>();
List<TablePKEntity> list_PK = GetTablePK(tablename);
string strPK = "";
string strpk_name = "";
foreach (TablePKEntity pk in list_PK)
{
strPK += pk.PK_ColumnName + ",";
}
if (list_PK != null && list_PK.Count > )
{
if (!string.IsNullOrWhiteSpace(list_PK[].PK_Name))
{
strpk_name = list_PK[].PK_Name;
}
}
strPK = strPK.TrimEnd(',');
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow dr in dt.Rows)
{
TableInfoEntity entity = new TableInfoEntity() ;
entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t", "");
entity.ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
entity.TypeName = dr["TYPE_NAME"].ToString();
entity.Precision = Convert.ToInt32(dr["PRECISION"].ToString());
entity.SCALE = dr["SCALE"] == System.DBNull.Value ? : Convert.ToInt32(dr["SCALE"].ToString());
entity.Nullable = dr["NULLABLE"].ToString().Trim() == "" ? false : true;
entity.IsIdentity = dr["TYPE_NAME"].ToString().Contains("identity") ? true : false;
entity.IsPK = list_PK.Where(q => q.PK_ColumnName == dr["COLUMN_NAME"].ToString()).Count() > ? true : false;
entity.PKColumn = strPK;
entity.PK_Name = strpk_name.Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace("\t","").Replace(".","");
list.Add(entity);
}
} return list;
} /// <summary>
/// 獲取表格的主鍵
/// </summary>
/// <param name="tablename">表格名稱</param>
/// <returns></returns>
public List<TablePKEntity> GetTablePK(string tablename)
{
string strProc = "sp_pkeys";
SqlParameter[] parameters = {
new SqlParameter("@table_name", SqlDbType.VarChar,)
};
parameters[].Value = tablename;
DataTable dt = DbHelperSQL.RunProcedure(strProc, parameters, tablename).Tables[];
List<TablePKEntity> list = new List<TablePKEntity>();
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow dr in dt.Rows)
{
TablePKEntity entity = new TablePKEntity();
entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t","");
entity.PK_ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
entity.PK_Name = dr["PK_NAME"].ToString();
list.Add(entity);
}
}
return list;
} public DataTable GetTableData(string querySql)
{
DataTable dt = DbHelperSQL.Query(querySql).Tables[];
return dt;
} public int ExcuteSql(List<string> sql)
{
return DbHelperSQL.ExecuteSqlTran(sql);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;
using System.Data; namespace SQL2Sqlite
{
public class BaseHelper
{
//日志文件生命周期的时间标记
//private static DateTime TimeSign;
public Dictionary<string, string> dicSqlInsert = new Dictionary<string, string>();
public Dictionary<string, string> dicSqlQuery = new Dictionary<string, string>();
private string GetDBName()
{
DateTime now = DateTime.Now; string name = "FB_Proposal" + now.ToString("yyyyMMdd") + ".db";
if (!File.Exists(name))
{
//創建DB
createNewDatabase(name);
//創建Table
//CreateTable(name);
}
return name;
}
//创建一个空的数据库
private void createNewDatabase(string name)
{
SQLiteConnection.CreateFile(name);
}
private void CreateTable(string name)
{
string sql = "create table YouKeyBorad (addtime INTEGER, keyvalue varchar(10));create table YouScreen (addtime INTEGER, screenimg TEXT)";
SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", name));
SQLiteCommand command = new SQLiteCommand(sql, conn);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
public SQLiteConnection Connect()
{
SQLiteConnection m_dbConnection = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", GetDBName()));
return m_dbConnection;
} public bool CreateTable2(string tablename)
{ bool retbool = false;
StringBuilder strSql = new StringBuilder();
//生成 插入數據的SQl語句
StringBuilder strSql_insert = new StringBuilder();
StringBuilder strSql_Query = new StringBuilder();
try
{
strSql.Append(" create table ");
strSql.Append("[" + tablename.TrimEnd() + "]");
strSql.Append(" ( ");
DBParse dbSQL = new DBParse();
List<TableInfoEntity> list = dbSQL.GetTableInfo(tablename);
//foreach (TableInfoEntity entity in list)
string strPK = "";
string strpk_name = "";
strSql_insert.AppendFormat(" insert into {0} values(", tablename);
strSql_Query.Append("select ");
//拼接創建表的SQL
for (int i = ; i < list.Count; i++)
{
TableInfoEntity entity = list[i];
#region 拼接創建表 SQL
strSql.Append("[" + entity.ColumnName + "]");
strSql.Append(" ");
strSql.Append(SQLType2SQLiteType.SqlTypeString2SqliteType(entity.TypeName, entity.Precision, entity.SCALE)); if (!entity.Nullable)
{
strSql.Append(" NOT NULL ");
} //if (entity.IsIdentity)
//{
// strSql.Append(" AUTOINCREMENT ");
//}
#endregion
#region 拼接插入數據的SQL
if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
|| entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
|| entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
|| entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
|| entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
{
strSql_insert.Append(" '{");
}
else
{
strSql_insert.Append(" {");
}
if (entity.TypeName.Equals("System.DateTime") || entity.TypeName.ToLower().Contains("datetime"))
{
strSql_insert.Append(i + ":yyyy-MM-dd HH:mm:ss.fff");
}
else
{
strSql_insert.Append(i);
}
//strSql_insert.Append(i);
if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
|| entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
|| entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
|| entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
|| entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
{
strSql_insert.Append("}'");
}
else
{
strSql_insert.Append("}");
}
#endregion
#region 拼接查詢數據的SQL
strSql_Query.Append("[" + entity.ColumnName + "]");
#endregion
if (i < list.Count - )
{
strSql.Append(",");
strSql_insert.Append(",");
strSql_Query.Append(",");
}
strPK = entity.PKColumn;
strpk_name = entity.PK_Name;
}
//給表添加主鍵
if (strPK != "")
{
if (strpk_name.Trim() == "")
{
strpk_name = "pk_" + tablename.TrimEnd();
}
strSql.AppendFormat(" ,constraint {0} primary key ({1}) ", strpk_name, strPK);
}
strSql.Append(" ) ");
strSql_insert.Append(" );");
strSql_Query.Append(" from " + tablename.TrimEnd());
SQLiteHelper.ExecuteNonQuery(Connect(), strSql.ToString());
retbool = true;
dicSqlInsert.Add(tablename.TrimEnd(), strSql_insert.ToString());
dicSqlQuery.Add(tablename.TrimEnd(), strSql_Query.ToString());
}
catch (Exception ee)
{
MyConsole.WriteLine(ee.Message + "----" + strSql.ToString());
retbool = false;
}
return retbool;
} public int ImportData(string querySql,string intoSql)
{
int retInt = ;
DBParse dbSQL = new DBParse();
DataTable dtSqlData = dbSQL.GetTableData(querySql);
//最後的執行insert的SQL語句
List<string> listSql = new List<string>();
if (dtSqlData != null && dtSqlData.Rows.Count > )
{
for (int i = ; i < dtSqlData.Rows.Count; i++)
{
try
{
string sqlTemp = "";
object[] args = new object[dtSqlData.Columns.Count];
object objtemp = null;
bool haveNull = false;
for (int j = ; j < dtSqlData.Columns.Count; j++)
{
//MyConsole.TransferEncoding(Encoding.Default, Encoding.UTF8, dtSqlData.Rows[i][j].ToString());
if (intoSql.Contains("PIA_LOG_MAIN"))
{
break;
}
//if (intoSql.Contains("tbNews"))
//{
// int x = 0;
//}
if (dtSqlData.Rows[i][j] == DBNull.Value || dtSqlData.Columns[j].DataType == Type.GetType("System.Byte[]"))
{
args[j] = "Null";
sqlTemp = intoSql.Replace("'{" + j + "}'", "{" + j + "}");
haveNull = true;
}
else if (dtSqlData.Columns[j].DataType == Type.GetType("System.Boolean"))
{
args[j] = Convert.ToBoolean(dtSqlData.Rows[i][j]) ? : ;
}
else
{
if (dtSqlData.Rows[i][j].ToString().Contains(@"'"))
{
args[j] = dtSqlData.Rows[i][j].ToString().Replace(@"'", @"''");
}
else
{
args[j] = dtSqlData.Rows[i][j];
}
}
}
string into_temp = "";
if (haveNull)
{
into_temp = string.Format(sqlTemp, args);
}
else
{
into_temp = string.Format(intoSql, args);
}
//string into_temp = string.Format(intoSql, args);
listSql.Add(into_temp.Replace("'Null'","Null"));
if (listSql.Count == )
{
int temp = ExecuteSQL(listSql);
if (temp == )
{
Logger.Error(listSql.ToString());
MyConsole.WriteLine("有500條導入數據的事務出現異常,已放棄:" + intoSql);
}
retInt += temp;
listSql.Clear();
}
}
catch (Exception ex)
{
MyConsole.WriteLine(ex.Message);
}
}
if (listSql.Count > )
{
//retInt += ExecuteSQL(listSql);
int temp = ExecuteSQL(listSql);
if (temp == )
{
MyConsole.WriteLine("有部分導入數據的事務出現異常,已放棄:" + intoSql);
}
retInt += temp;
}
}
return retInt;
} private int ExecuteSQL(List<string> intoSql)
{
return SQLiteHelper.ExecuteSqlTran(Connect(),intoSql);
} }
}
從數據庫中得到數據
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient; namespace SQL2Sqlite
{
public class DBParse
{
/// <summary>
/// 獲取DB中所有的表格
/// </summary>
/// <returns></returns>
public List<TableEntity> GetAllTable()
{
string sql = "SELECT Name FROM SysObjects Where XType='U' ORDER BY Name";
DataTable dt = DbHelperSQL.Query(sql).Tables[];
List<TableEntity> list = new List<TableEntity>();
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow dr in dt.Rows)
{
TableEntity entity = new TableEntity() { TableName = dr["Name"].ToString() };
list.Add(entity);
}
} return list;
} public List<TableInfoEntity> GetTableInfo(string tablename)
{
string strProc = "sp_columns";
SqlParameter[] parameters = {
new SqlParameter("@table_name", SqlDbType.VarChar,)
};
parameters[].Value = tablename;
DataTable dt = DbHelperSQL.RunProcedure(strProc,parameters,tablename).Tables[];
List<TableInfoEntity> list = new List<TableInfoEntity>();
List<TablePKEntity> list_PK = GetTablePK(tablename);
string strPK = "";
string strpk_name = "";
foreach (TablePKEntity pk in list_PK)
{
strPK += pk.PK_ColumnName + ",";
}
if (list_PK != null && list_PK.Count > )
{
if (!string.IsNullOrWhiteSpace(list_PK[].PK_Name))
{
strpk_name = list_PK[].PK_Name;
}
}
strPK = strPK.TrimEnd(',');
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow dr in dt.Rows)
{
TableInfoEntity entity = new TableInfoEntity() ;
entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t", "");
entity.ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
entity.TypeName = dr["TYPE_NAME"].ToString();
entity.Precision = Convert.ToInt32(dr["PRECISION"].ToString());
entity.SCALE = dr["SCALE"] == System.DBNull.Value ? : Convert.ToInt32(dr["SCALE"].ToString());
entity.Nullable = dr["NULLABLE"].ToString().Trim() == "" ? false : true;
entity.IsIdentity = dr["TYPE_NAME"].ToString().Contains("identity") ? true : false;
entity.IsPK = list_PK.Where(q => q.PK_ColumnName == dr["COLUMN_NAME"].ToString()).Count() > ? true : false;
entity.PKColumn = strPK;
entity.PK_Name = strpk_name.Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace(" ", "").Replace("\t","").Replace(".","");
list.Add(entity);
}
} return list;
} /// <summary>
/// 獲取表格的主鍵
/// </summary>
/// <param name="tablename">表格名稱</param>
/// <returns></returns>
public List<TablePKEntity> GetTablePK(string tablename)
{
string strProc = "sp_pkeys";
SqlParameter[] parameters = {
new SqlParameter("@table_name", SqlDbType.VarChar,)
};
parameters[].Value = tablename;
DataTable dt = DbHelperSQL.RunProcedure(strProc, parameters, tablename).Tables[];
List<TablePKEntity> list = new List<TablePKEntity>();
if (dt != null && dt.Rows.Count > )
{
foreach (DataRow dr in dt.Rows)
{
TablePKEntity entity = new TablePKEntity();
entity.TableName = dr["TABLE_NAME"].ToString().Trim().Replace("\t","");
entity.PK_ColumnName = dr["COLUMN_NAME"].ToString().Trim().Replace("\t", "");
entity.PK_Name = dr["PK_NAME"].ToString();
list.Add(entity);
}
}
return list;
} public DataTable GetTableData(string querySql)
{
DataTable dt = DbHelperSQL.Query(querySql).Tables[];
return dt;
} public int ExcuteSql(List<string> sql)
{
return DbHelperSQL.ExecuteSqlTran(sql);
}
}
}
得到表的信息
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace SQL2Sqlite
{
public class Entity
{ } /// <summary>
/// 數據庫內所有的表格
/// </summary>
public class TableEntity
{
public string TableName { get; set; }
} /// <summary>
/// 表格對象
/// </summary>
public class TableInfoEntity
{
/// <summary>
/// 表名
/// </summary>
public string TableName { get; set; }
/// <summary>
/// 列名
/// </summary>
public string ColumnName { get; set; }
/// <summary>
/// 列類型名
/// </summary>
public string TypeName { get; set; }
/// <summary>
/// 列類型的長度
/// </summary>
public int Precision { get; set; } /// <summary>
/// 列類型的小數位
/// </summary>
public int SCALE { get; set; } /// <summary>
/// 列是否可以為空 true可以為空,false不能為空
/// </summary>
public bool Nullable { get; set; } /// <summary>
/// 是否自動增長 true為自動增長
/// </summary>
public bool IsIdentity { get; set; } /// <summary>
/// 是否為主鍵 true為主鍵
/// </summary>
public bool IsPK { get; set; } /// <summary>
/// 所有的主鍵列,逗號隔開
/// </summary>
public string PKColumn { get; set; }
/// <summary>
/// 主鍵名
/// </summary>
public string PK_Name { get; set; } } /// <summary>
/// 表格主鍵名
/// </summary>
public class TablePKEntity
{
/// <summary>
/// 表名
/// </summary>
public string TableName { get; set; }
/// <summary>
/// 主鍵列名
/// </summary>
public string PK_ColumnName { get; set; } /// <summary>
/// 主鍵名
/// </summary>
public string PK_Name { get; set; }
}
}
實體
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;
using System.Data; namespace SQL2Sqlite
{
public class BaseHelper
{
//日志文件生命周期的时间标记
//private static DateTime TimeSign;
public Dictionary<string, string> dicSqlInsert = new Dictionary<string, string>();
public Dictionary<string, string> dicSqlQuery = new Dictionary<string, string>();
private string GetDBName()
{
DateTime now = DateTime.Now; string name = "FB_Proposal" + now.ToString("yyyyMMdd") + ".db";
if (!File.Exists(name))
{
//創建DB
createNewDatabase(name);
//創建Table
//CreateTable(name);
}
return name;
}
//创建一个空的数据库
private void createNewDatabase(string name)
{
SQLiteConnection.CreateFile(name);
}
private void CreateTable(string name)
{
string sql = "create table YouKeyBorad (addtime INTEGER, keyvalue varchar(10));create table YouScreen (addtime INTEGER, screenimg TEXT)";
SQLiteConnection conn = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", name));
SQLiteCommand command = new SQLiteCommand(sql, conn);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
public SQLiteConnection Connect()
{
SQLiteConnection m_dbConnection = new SQLiteConnection(string.Format("Data Source={0};Version=3;UseUTF8Encoding=True;", GetDBName()));
return m_dbConnection;
} public bool CreateTable2(string tablename)
{ bool retbool = false;
StringBuilder strSql = new StringBuilder();
//生成 插入數據的SQl語句
StringBuilder strSql_insert = new StringBuilder();
StringBuilder strSql_Query = new StringBuilder();
try
{
strSql.Append(" create table ");
strSql.Append("[" + tablename.TrimEnd() + "]");
strSql.Append(" ( ");
DBParse dbSQL = new DBParse();
List<TableInfoEntity> list = dbSQL.GetTableInfo(tablename);
//foreach (TableInfoEntity entity in list)
string strPK = "";
string strpk_name = "";
strSql_insert.AppendFormat(" insert into {0} values(", tablename);
strSql_Query.Append("select ");
//拼接創建表的SQL
for (int i = ; i < list.Count; i++)
{
TableInfoEntity entity = list[i];
#region 拼接創建表 SQL
strSql.Append("[" + entity.ColumnName + "]");
strSql.Append(" ");
strSql.Append(SQLType2SQLiteType.SqlTypeString2SqliteType(entity.TypeName, entity.Precision, entity.SCALE)); if (!entity.Nullable)
{
strSql.Append(" NOT NULL ");
} //if (entity.IsIdentity)
//{
// strSql.Append(" AUTOINCREMENT ");
//}
#endregion
#region 拼接插入數據的SQL
if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
|| entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
|| entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
|| entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
|| entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
{
strSql_insert.Append(" '{");
}
else
{
strSql_insert.Append(" {");
}
if (entity.TypeName.Equals("System.DateTime") || entity.TypeName.ToLower().Contains("datetime"))
{
strSql_insert.Append(i + ":yyyy-MM-dd HH:mm:ss.fff");
}
else
{
strSql_insert.Append(i);
}
//strSql_insert.Append(i);
if (entity.TypeName.ToLower().Equals("varchar") || entity.TypeName.ToLower().Equals("ntext")
|| entity.TypeName.ToLower().Equals("nvarchar") || entity.TypeName.ToLower().Equals("text")
|| entity.TypeName.ToLower().Equals("char") || entity.TypeName.ToLower().Equals("nchar")
|| entity.TypeName.ToLower().Equals("bit") || entity.TypeName.ToLower().Equals("datetime")
|| entity.TypeName.ToLower().Equals("date") || entity.TypeName.ToLower().Equals("time"))
{
strSql_insert.Append("}'");
}
else
{
strSql_insert.Append("}");
}
#endregion
#region 拼接查詢數據的SQL
strSql_Query.Append("[" + entity.ColumnName + "]");
#endregion
if (i < list.Count - )
{
strSql.Append(",");
strSql_insert.Append(",");
strSql_Query.Append(",");
}
strPK = entity.PKColumn;
strpk_name = entity.PK_Name;
}
//給表添加主鍵
if (strPK != "")
{
if (strpk_name.Trim() == "")
{
strpk_name = "pk_" + tablename.TrimEnd();
}
strSql.AppendFormat(" ,constraint {0} primary key ({1}) ", strpk_name, strPK);
}
strSql.Append(" ) ");
strSql_insert.Append(" );");
strSql_Query.Append(" from " + tablename.TrimEnd());
SQLiteHelper.ExecuteNonQuery(Connect(), strSql.ToString());
retbool = true;
dicSqlInsert.Add(tablename.TrimEnd(), strSql_insert.ToString());
dicSqlQuery.Add(tablename.TrimEnd(), strSql_Query.ToString());
}
catch (Exception ee)
{
MyConsole.WriteLine(ee.Message + "----" + strSql.ToString());
retbool = false;
}
return retbool;
} public int ImportData(string querySql,string intoSql)
{
int retInt = ;
DBParse dbSQL = new DBParse();
DataTable dtSqlData = dbSQL.GetTableData(querySql);
//最後的執行insert的SQL語句
List<string> listSql = new List<string>();
if (dtSqlData != null && dtSqlData.Rows.Count > )
{
for (int i = ; i < dtSqlData.Rows.Count; i++)
{
try
{
string sqlTemp = "";
object[] args = new object[dtSqlData.Columns.Count];
object objtemp = null;
bool haveNull = false;
for (int j = ; j < dtSqlData.Columns.Count; j++)
{
//MyConsole.TransferEncoding(Encoding.Default, Encoding.UTF8, dtSqlData.Rows[i][j].ToString());
if (intoSql.Contains("PIA_LOG_MAIN"))
{
break;
}
//if (intoSql.Contains("tbNews"))
//{
// int x = 0;
//}
if (dtSqlData.Rows[i][j] == DBNull.Value || dtSqlData.Columns[j].DataType == Type.GetType("System.Byte[]"))
{
args[j] = "Null";
sqlTemp = intoSql.Replace("'{" + j + "}'", "{" + j + "}");
haveNull = true;
}
else if (dtSqlData.Columns[j].DataType == Type.GetType("System.Boolean"))
{
args[j] = Convert.ToBoolean(dtSqlData.Rows[i][j]) ? : ;
}
else
{
if (dtSqlData.Rows[i][j].ToString().Contains(@"'"))
{
args[j] = dtSqlData.Rows[i][j].ToString().Replace(@"'", @"''");
}
else
{
args[j] = dtSqlData.Rows[i][j];
}
}
}
string into_temp = "";
if (haveNull)
{
into_temp = string.Format(sqlTemp, args);
}
else
{
into_temp = string.Format(intoSql, args);
}
//string into_temp = string.Format(intoSql, args);
listSql.Add(into_temp.Replace("'Null'","Null"));
if (listSql.Count == )
{
int temp = ExecuteSQL(listSql);
if (temp == )
{
Logger.Error(listSql.ToString());
MyConsole.WriteLine("有500條導入數據的事務出現異常,已放棄:" + intoSql);
}
retInt += temp;
listSql.Clear();
}
}
catch (Exception ex)
{
MyConsole.WriteLine(ex.Message);
}
}
if (listSql.Count > )
{
//retInt += ExecuteSQL(listSql);
int temp = ExecuteSQL(listSql);
if (temp == )
{
MyConsole.WriteLine("有部分導入數據的事務出現異常,已放棄:" + intoSql);
}
retInt += temp;
}
}
return retInt;
} private int ExecuteSQL(List<string> intoSql)
{
return SQLiteHelper.ExecuteSqlTran(Connect(),intoSql);
} }
}
得到SQL插入语句
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 SQL2Sqlite
{
/// <summary>
/// 数据访问抽象基础类
/// Copyright (C) Maticsoft
/// </summary>
public abstract class DbHelperSQL
{
//数据库连接字符串(web.config来配置),多数据库可使用DbHelperSQLP来实现.
private static string connectionString = ConfigurationManager.AppSettings["DefaultConnection"].ToString();//PubConstant.ConnectionString; public static string ConnectionString
{
get { return connectionString;/*DbHelperSQL.connectionString;*/ }
//set { DbHelperSQL.connectionString = value; }
}
public DbHelperSQL()
{
} #region 公用方法 /// <summary>
/// 判断是否存在某表的某个字段
/// </summary>
/// <param name="tableName">表名称</param>
/// <param name="columnName">列名称</param>
/// <returns>是否存在</returns>
public static 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) > ;
}
public static int GetMaxID(string FieldName, string TableName)
{
string strsql = "select max(" + FieldName + ")+1 from " + TableName;
object obj = GetSingle(strsql);
if (obj == null)
{
return ;
}
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 = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// 表是否存在
/// </summary>
/// <param name="TableName"></param>
/// <returns></returns>
public static 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 = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
return false;
}
else
{
return true;
}
}
public static 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 = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
if (cmdresult == )
{
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 (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 static 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>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">多条SQL语句</param>
public static 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 = ;
for (int n = ; n < SQLStringList.Count; n++)
{
string strsql = SQLStringList[n];
if (strsql.Trim().Length > )
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
}
tx.Commit();
return count;
}
catch
{
tx.Rollback();
return ;
}
}
}
/// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static 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>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static 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>
/// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static 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>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static 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 static 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>
/// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static 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>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static 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 static 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 执行带参数的SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static 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>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
//循环
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>
///// 执行多条SQL语句,实现数据库事务。
///// </summary>
///// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
//public static 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;
// //循环
// 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>
///// 执行多条SQL语句,实现数据库事务。
///// </summary>
///// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
//public static 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;
// //循环
// 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>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[])</param>
public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
int indentity = ;
//循环
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>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static 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>
/// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="strSQL">查询语句</param>
/// <returns>SqlDataReader</returns>
public static 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;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// } } /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static 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 static 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 存储过程操作 /// <summary>
/// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlDataReader</returns>
public static 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>
/// 执行存储过程
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="tableName">DataSet结果中的表名</param>
/// <returns>DataSet</returns>
public static 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 static 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>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static 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)
{
// 检查未分配值的输出参数,将其分配以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>
/// 执行存储过程,返回影响的行数
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <param name="rowsAffected">影响的行数</param>
/// <returns></returns>
public static 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;
//Connection.Close();
return result;
}
} /// <summary>
/// 创建 SqlCommand 对象实例(用来返回一个整数值)
/// </summary>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand 对象实例</returns>
private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
command.Parameters.Add(new SqlParameter("ReturnValue",
SqlDbType.Int, , ParameterDirection.ReturnValue,
false, , , string.Empty, DataRowVersion.Default, null));
return command;
}
#endregion } }
DBHelper
使用entitiy的更多相关文章
- VS 2015 (RC)下Entitiy Framework 升级后CodeFirst命令不能使用
前阵子闲的没事吧自己项目的Entitiy Framework 升级到6.1.3了,然后紧接着问题来了: Join-Path : 无法将参数绑定到参数“Path”,因为该参数是空值. 所在位置 F:\S ...
- Entitiy Framework Core中使用ChangeTracker持久化实体修改历史
背景介绍 在我们的日常开发中,有时候需要记录数据库表中值的变化, 这时候我们通常会使用触发器或者使用关系型数据库中临时表(Temporal Table)或数据变更捕获(Change Data Capt ...
- Hibernate —— 映射关联关系
一.映射多对一关联关系. 1.单向的多对一 (1)以 Customer 和 Order 为例:一个用户可以发出多个订单,而一个订单只能属于一个客户.从 Order 到 Customer 是多对一关联关 ...
- C#进阶系列——MEF实现设计上的“松耦合”(二)
前言:前篇 C#进阶系列——MEF实现设计上的“松耦合”(一) 介绍了下MEF的基础用法,让我们对MEF有了一个抽象的认识.当然MEF的用法可能不限于此,比如MEF的目录服务.目录筛选.重组部件等高级 ...
- 自定义一个可复用的BaseAdapter
1.我们一点点开始改: 首先我们自定义BaseAdapter,等下我们就要对他进行升级改造 /** * Created by Jay on 2015/9/21 0021. */ public clas ...
- 关系型数据之LinQ基本查询
如下图所示关系型数据,LinQ语句为:
- mybatis generator配置生成代码的问题
接触第二种orm两天下来,一脸懵逼.mybatis是大多数公司所推崇的,相比于hibernate性能较为好的,操作更为方便的轻量级工具,所以小富就搞起这个orm.好吧,都说mybatis有个配置可以自 ...
- 总结一下工作中用到的Mybatis业务逻辑
1.简单说明. MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO( Plain Old Java Objects,普通的Java 对象)映射成数据库中的 ...
- LINQ的左连接、右连接、内连接
.左连接: var LeftJoin = from emp in ListOfEmployees join dept in ListOfDepartment on emp.DeptID equals ...
随机推荐
- ELK Packetbeat 部署指南
http://www.ttlsa.com/elk/elk-packetbeat-deployment-guide/
- GridView的stretchMode属性
stretchMode属性值的作用是设置GridView中的条目以什么缩放模式去填充剩余空间.参数stretchMode 可选值为:none,spacingWidth,columnWidth, spa ...
- Confluence 6 WebDAV 禁用严格路径检查
如果你在你的 WebDAV 客户端发现了一些不正常的现象,例如文件夹在 Confluence 中是存在的,但是在你客户端下载的文件中就不存在了.你可以禁用 WebDAV 插件中的严格路径检查选项,这 ...
- Confluence 6 恢复一个站点问题解决
如果你在导入的时候遇到了问题,检查下面的一些提示. 你的文件太大而不能上传?这个是非常常见的错误.出现的原因是备份文件不能在规定的时间内上传到服务器上.为了避免这个错误,放置你的导出文件到 < ...
- 开源中国社区 https://git.oschina.net/ 添加 SSH 公钥 添加
首先可以参考官方的帮助文档 http://git.mydoc.io/?t=154712 然后进去码云首页 http://git.oschina.net 然后找到右边的头像点击一下 然后点击修改资料 ...
- (五)STL算法
.算法 1.算法通过迭代器来操作容器中的数据: 2.算法为模板函数: 二.迭代器与算法 1.根据移动能力,将迭代器分成了五类 2.使用萃取,输出各个容器中,迭代器的类别 3.其中istream, os ...
- Selenium WebDriver中鼠标事件
鼠标点击操作 鼠标点击事件有以下几种类型: 清单 1. 鼠标左键点击 Actions action = new Actions(driver);action.click();// 鼠标左键在当 ...
- Netty沾包和拆包
1.连着发两条,会沾在一起,这就是沾包 2.包尾添加特殊分隔符,接收方通过特殊分隔符切分报文区分,这就是拆包 在ChatServerInit类.ChatClientInit类分别加入以下代码 Byte ...
- 整合Flask中的目录结构
一.SQLAlchemy-Utils 由于sqlalchemy中没有提供choice方法,所以借助SQLAlchemy-Utils组件提供的choice方法 import datetime from ...
- CF1121C 模拟
恶心场恶心题,,round千万不能用库函数的.. /*枚举时间轴t,r是当前完成比例, 记录每个测试的开始时间si,如果有t-si等于r,那么这个测试就标记一下 优先队列存储每个测试,按照si+ai的 ...