使用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 ...
随机推荐
- python时间日期格式化和反格式化
strftime()和strptime()行为 date,datetime和time对象都支持一种 strftime(format)方法,以创建一个表示显式格式字符串控制下的时间的字符串.从广义上讲, ...
- 修复ogg source端意外宕机造成的数据不同步
修复ogg source端意外宕机造成的数据不同步 分类: Oracle2016-04-28 11:50:40原文地址:修复ogg source端意外宕机造成的数据不同步 作者:十字螺丝钉 ogg s ...
- input file 多张图片上传 获取地址 ——fileReader
//上传图片 $('#files').change(function(e){ var fil = this.files; var m =0; if(fil.length>3){ alert('重 ...
- 用sqlplus为oracle创建用户和表空间
用Oracle自带的企业管理器或PL/SQL图形化的方法创建表空间和用户以及分配权限是相对比较简单的, 本文要介绍的是另一种方法就是使用Oracle所带的命令行工具SQLPLUS来创建表空间. 打开S ...
- Confluence 6 查看索引和提示
查看索引 Confluence 使用被称为 Lucene 的搜索引擎.如果你希望在你的 Confluence站点中查看更多有关索引的细节,你可以下载并且运行 Luke.Luke 是一个开发和诊断工具, ...
- Confluence 6 后台中为站点添加应用导航
Confluence 6 后台中为站点添加应用导航的连界面和方法. https://www.cwiki.us/display/CONFLUENCEWIKI/Configuring+the+Site+H ...
- SpringBoot的yml配置文件
1.在src\main\resources下创建application.yml配置文件 spring: datasource: driver-class-name: com.mysql.jdbc.Dr ...
- txt提取相同内容、不同内容
findstr >相同部分.txt findstr >%~n2多余部分.txt findstr >%~n1多余部分.txt
- 开放系统的直连式存储(Direct-Attached Storage,简称DAS)
开放系统的直连式存储(Direct-Attached Storage,简称DAS)已经有近四十年的使用历史,随着用户数据的不断增长,尤其是数百GB以上时,其在备份.恢复.扩展.灾备等方面的问题变得日益 ...
- 没有-jackson相关依赖会抛出如下异常--------在spring官方文档有解释
<!--jackson相关依赖--><!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackso ...