using System;using System.Data;using System.Data.SqlClient;namespace Whir.Software.Framework.Ultimate{ ////// 数据库访问助手 /// public class DbHelper { #region 判断连接是否成功 ////// 判断连接是否成功! /// /// 链接字符串 ///true 表示链接成功,false表示连接失败 public static bool IsConnected(string con) { bool flag; var conn = new SqlConnection(con); try { conn.Open(); flag = true; } catch (Exception) { flag = false; } finally { conn.Close(); } return flag; } #endregion #region 执行不带参数sql语句 ////// 执行不带参数sql语句 /// /// 增,删,改sql语句 /// ///返回所影响的行数 public static bool Execute(string sql, string con) { var cmd = new SqlCommand(); var connection = new SqlConnection(con); try { using (connection) { cmd.Connection = connection; cmd.CommandText = sql; connection.Open(); cmd.ExecuteNonQuery(); return true; } } catch (Exception) { return false; } } #endregion #region 执行SQL语句返回DataTable ////// 执行SQL语句返回DataTable /// /// /// ///public static DataTable ExcuteDataTable(string sql, string con) { var cmd = new SqlCommand(); var connection = new SqlConnection(con); try { using (connection) { cmd.Connection = connection; cmd.CommandText = sql; connection.Open(); var da = new SqlDataAdapter(cmd); var ds = new DataSet(); da.Fill(ds); return ds.Tables[0]; } } catch (Exception ex) { var dt = new DataTable(); dt.Columns.Add("异常信息"); DataRow row = dt.NewRow(); row["异常信息"] = ex.Message; dt.Rows.Add(row); return dt; } } #endregion #region 执行SQL语句查询单条记录 /// /// 执行SQL语句查询单条记录 /// /// /// ///public static object ExecuteScalar(string sql, string con) { var cmd = new SqlCommand(); var connection = new SqlConnection(con); try { using (connection) { cmd.Connection = connection; cmd.CommandText = sql; connection.Open(); return cmd.ExecuteScalar(); } } catch (Exception) { return string.Empty; } } #endregion #region 取得表最大Id /// /// 取得表最大Id /// /// /// /// ///public static int GetMaxId(string tableName, string fieldName, string con) { string sql = "SELECT NVL(MAX({0}),0)+1 FROM {1}"; try { sql = string.Format(sql, fieldName, tableName); int result; Int32.TryParse(ExecuteScalar(sql, con).ToString(), out result); return result; } catch (Exception) { return -1; } } #endregion }}
作者:a497785609 发表于2014-6-1 15:06:22
阅读:8 评论:0