using System;
using System.Data;
using System.Data.SqlClient;
namespace Whir.Software.Framework.Ultimate
{
/// <summary>
///     ?????????????
/// </summary>
public class DbHelper
{
#region ?ж??????????
/// <summary>
///     ?ж????????????
/// </summary>
/// <param name="con"> ?????????</param>
/// <returns>true ???????????false??????????</returns>
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???
/// <summary>
///     ??в???????sql???
/// </summary>
/// <param name="sql">?????????sql???</param>
/// <param name="con"></param>
/// <returns>??????????????</returns>
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
/// <summary>
///     ???SQL?????DataTable
/// </summary>
/// <param name="sql"></param>
/// <param name="con"></param>
/// <returns></returns>
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????????????
/// <summary>
///     ???SQL????????????
/// </summary>
/// <param name="sql"></param>
/// <param name="con"></param>
/// <returns></returns>
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
/// <summary>
///     ?????Id
/// </summary>
/// <param name="tableName"></param>
/// <param name="fieldName"></param>
/// <param name="con"></param>
/// <returns></returns>
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
}
}