using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.OleDb; using System.Web; using System.Collections; using System.Configuration; using System.Drawing; using System.IO; using System.Data.SqlClient; namespace DBTool { public class DB { public static OleDbConnection conn = null; public static string GetConnStringOut() { string s = System.Configuration.ConfigurationManager.ConnectionStrings["smconn"].ConnectionString.ToString(); return s; } public static string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; public string GetConnString() { string s = System.Configuration.ConfigurationManager.ConnectionStrings["smconn"].ConnectionString.ToString(); return s; } /// <summary> /// 打开数据库连接 /// </summary> public void OpenConn() { try { //if (conn == null) //{ conn = new OleDbConnection(); conn.ConnectionString = this.GetConnString(); // } //if (conn != null && conn.State == ConnectionState.Closed) conn.Open(); } catch { } } /// <summary> /// 关闭数据库连接 /// </summary> public void CloseConn() { if (conn != null && conn.State == ConnectionState.Open) conn.Close(); conn.Dispose(); } /// <summary> /// 执行查询返回DataTable /// </summary> /// <param name="sql">要执行查询的sql语句</param> /// <returns>DataTable</returns> public DataTable RunSqlGetDataTable(string sql) { using (SqlConnection connection = new SqlConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); SqlDataAdapter command = new SqlDataAdapter(sql, connection); command.Fill(ds, "ds"); } catch (System.Data.SqlClient.SqlException ex) { throw new Exception(ex.Message); } return ds.Tables[0]; } } /// <summary> /// 执行非查询返回影响行数 /// </summary> /// <param name="sql">要执行非查询的sql语句</param> /// <returns> int </returns> public int RunSqlGetRowCount(string sql) { OpenConn(); OleDbCommand cmd = new OleDbCommand(sql, conn); int rowcount = -1; try { rowcount = cmd.ExecuteNonQuery(); } catch (OleDbException ex) { string sTmp = ex.Message.ToLower(); if (sTmp.IndexOf("重复键") >= 0) { //MessageBox.Show("不允许重复!"); } else if (sTmp.IndexOf("reference") >= 0) { //MessageBox.Show("数据已经被使用!"); } else { rowcount = -3;//主要是为了在系统重建的时候使用 } } catch { } CloseConn(); return rowcount; } /// <summary> /// Execute a SqlCommand that returns a resultset against the database specified in the connection string /// using the provided parameters. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param> /// <param name="cmdText">存储过程的名字或者 T-SQL 语句</param> /// <param name="commandParameters">以数组形式提供SqlCommand命令中用到的参数列表</param> /// <returns>A SqlDataReader containing the results</returns> public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch (Exception ex) { conn.Close(); throw new Exception(ex.Message); } } private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, 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 = cmdType; if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } /// <summary> /// 执行非查询返回影响行数 /// </summary> /// <param name="sql">要执行非查询的sql语句 返回id</param> /// <returns> int </returns> public int RunSqlGetRowCountReturnId(string sql) { OpenConn(); OleDbCommand cmd = new OleDbCommand(sql, conn); object rowcount = "0"; try { rowcount = cmd.ExecuteScalar(); } catch (OleDbException ex) { string sTmp = ex.Message.ToLower(); if (sTmp.IndexOf("重复键") >= 0) { //MessageBox.Show("不允许重复!"); } else if (sTmp.IndexOf("reference") >= 0) { //MessageBox.Show("数据已经被使用!"); } else { rowcount = -3;//主要是为了在系统重建的时候使用 } } catch { } CloseConn(); return int.Parse(rowcount.ToString()); } /// <summary> /// 返回查询结果集中第一行第一列 /// </summary> /// <param name="sql">查询语句</param> /// <returns>object</returns> /// public object RunSqlGetObject(string sql) { OpenConn(); OleDbCommand cmd = new OleDbCommand(sql, conn); object o = cmd.ExecuteScalar(); CloseConn(); return o; } /// /// <summary> /// 获得一个具有事务功能的数据库连接对象 /// </summary> /// <param name="tconn"></param> /// <param name="transaction"></param> public void OpenTransConn(ref OleDbConnection tconn, ref OleDbTransaction transaction) { try { if (tconn == null) { tconn = new OleDbConnection(); tconn.ConnectionString = this.GetConnString(); } if (tconn != null && tconn.State == ConnectionState.Closed) { tconn.Open(); transaction = tconn.BeginTransaction(); } } catch { } } /// <summary> /// 关闭事务数据库连接 /// </summary> public void CloseTransConn(ref OleDbConnection tconn, ref OleDbTransaction transaction) { if (transaction != null) { transaction.Commit();//提交事务 } if (tconn != null && tconn.State == ConnectionState.Open) tconn.Close(); } public bool RunTransSqlGetBool(ref OleDbConnection tconn, ref OleDbTransaction transaction, string sql) { OleDbCommand cmd = new OleDbCommand(); cmd.Connection = tconn; cmd.CommandText = sql; cmd.Transaction = transaction; int rowcount = -1; try { rowcount = cmd.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.ErrorCode == -2147217873) { //MessageBox.Show("不能添加重复的值!"); } else { //MessageBox.Show("不能添加重复的值!"); } transaction.Rollback(); return false; } catch { } if (rowcount > 0) return true; return false; } //通过事务完成增加一系列记录 public bool RunTransSqls(ArrayList sqlAl) { int rowcount = -1; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = this.GetConnString(); OleDbTransaction tran = null; OleDbCommand cmd = null; #region MyRegion try { conn.Open(); tran = conn.BeginTransaction(); cmd = new OleDbCommand(); cmd.Connection = conn; cmd.Transaction = tran; cmd.CommandType = CommandType.Text; foreach (string sql in sqlAl) { //MessageBox.Show(sql); rowcount = -1; cmd.CommandText = sql; rowcount = cmd.ExecuteNonQuery(); if (rowcount <= 0)//有些时候是没有数据的,也算成功 { //tran.Rollback(); //return false; } } tran.Commit(); return true; } catch (Exception ex) { tran.Rollback(); //MessageBox.Show(ex.Message); } finally { try { if (conn != null && conn.State == ConnectionState.Open) conn.Close(); if (conn != null) conn.Dispose(); } catch { } } #endregion return false; } //通过存储过程 添加删除和修改 public int RunProcGetReturnValue(string procName, ArrayList al) { int re = 0; //数据库连接 OpenConn(); try { //定义命令对象 #region OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn;//关联数据库连接对象 cmd.CommandText = procName;//设置存储过程名称 cmd.CommandType = CommandType.StoredProcedure;//命令类型 #endregion cmd.Parameters.Clear(); //设置返回参数return , //注意:返回参数必须写在参数列表的第一个位置 OleDbParameter paramReturn = new OleDbParameter("returnvalue", OleDbType.VarChar, 50); paramReturn.Direction = ParameterDirection.ReturnValue;//参数传递方向;默认传入 paramReturn.Value = -1;//返回值 cmd.Parameters.Add(paramReturn);//增加返回参数到命令对象cmd foreach (OleDbParameter p in al) { cmd.Parameters.Add(p); } cmd.ExecuteNonQuery(); re = Convert.ToInt32(paramReturn.Value); } catch { } finally { CloseConn(); } return re; } public int RunProcGetOutputValue(string procName, ArrayList al) { //数据库连接 OpenConn(); //定义命令对象 #region OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn;//关联数据库连接对象 cmd.CommandText = procName;//设置存储过程名称 cmd.CommandType = CommandType.StoredProcedure;//命令类型 #endregion cmd.Parameters.Clear(); foreach (OleDbParameter p in al) { cmd.Parameters.Add(p); } try { return cmd.ExecuteNonQuery(); ; } catch { return 0; } finally { CloseConn(); } } //通过存储过程 查询(不带参数的查询) public DataSet RunProcGetDataTable(string procName) { //数据库连接 OpenConn(); //定义命令对象 #region ArrayList al = new ArrayList(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn;//关联数据库连接对象 cmd.CommandText = procName;//设置存储过程名称 cmd.CommandType = CommandType.StoredProcedure;//命令类型 #endregion cmd.Parameters.Clear(); foreach (OleDbParameter p in al) { cmd.Parameters.Add(p); } try { DataSet ds = new DataSet(); OleDbDataAdapter da = new OleDbDataAdapter(); da.SelectCommand = cmd; da.Fill(ds); return ds; } catch { return null; } finally { CloseConn(); } } // 通过存储过程查询数据(带参数的) public DataTable RunSqlGetDataTableFY(string name, int id) { OpenConn(); OleDbDataAdapter da = null; DataTable dt = null; OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; cmd.CommandText = name; ; cmd.CommandType = CommandType.StoredProcedure; OleDbParameter p2 = new OleDbParameter("@Id", OleDbType.Integer, 4); p2.Value = id; cmd.Parameters.Add(p2); try { da = new OleDbDataAdapter(); da.SelectCommand = cmd; dt = new DataTable(); da.Fill(dt); } catch { } CloseConn(); return dt; } public static OleDbConnection Getconn() { try { if (conn != null && conn.State == ConnectionState.Closed) conn.Open(); } catch { } return conn; } /// <summary> /// 导出报表文件为csv格式 /// </summary> public static bool DataDownTOcsv(string sql, string filename, string tableheader1, string tableheader2, string columname, int columcount) { try { string strFileToOrg = "", strBufferLine = "", strBufferLine1 = ""; int i; strFileToOrg = HttpContext.Current.Server.MapPath("~/pdf/" + filename + ".csv"); StreamWriter strmWriterObj = new StreamWriter(strFileToOrg, false, System.Text.Encoding.Default);//声明写入流对象 //OleDbConnection OleDbConnection1=new OleDbConnection(); OleDbConnection OleDbConnection1 = DB.Getconn(); //OleDbConnection1.ConnectionString="File Name="+HttpContext.Current.Server.MapPath("conn.udl"); //OleDbConnection1.Open(); OleDbCommand cmdGenFile = new OleDbCommand(); cmdGenFile.Connection = OleDbConnection1; cmdGenFile.CommandText = sql; OleDbDataReader drGenFile = cmdGenFile.ExecuteReader(); strmWriterObj.WriteLine(tableheader1); strmWriterObj.WriteLine(tableheader2); strmWriterObj.WriteLine(columname); while (drGenFile.Read()) { strBufferLine = ""; strBufferLine1 = Convert.ToString(drGenFile.GetValue(0)); strBufferLine = strBufferLine1; for (i = 1; i <= (columcount - 1); i++) { strBufferLine1 = ""; strBufferLine1 = Convert.ToString(drGenFile.GetValue(i)); strBufferLine = strBufferLine + "," + strBufferLine1; } strmWriterObj.WriteLine(strBufferLine); } strmWriterObj.Close(); drGenFile.Close(); return true; } catch { return false; } } /// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public bool MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW"://指定高宽缩放(可能变形) break; case "W"://指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H"://指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut"://指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); return true; } catch (System.Exception e) { throw e; return false; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } } }
时间: 2024-10-05 09:49:40