您的位置:首页 > 数据库

基于.net平台下数据库访问类(总结)

2014-05-20 20:58 316 查看
基于.net平台下的开发操作数据库方面都会用到数据库,以下介绍几种标准的数据库访问类。

1.组件式开发常用的数据库访问类

namespace Demo

{

class SQLHelp/////数据库访问类

{

//链接数据库字符串

public static string connString = @"server=.; database = *****(数据库名) ;User ID = sa(用户名); Pwd = 123(密码)";

public static readonly SqlConnection connection = new SqlConnection();

//链接数据库,打开并检查

public static void Connect()

{

try

{

connection.ConnectionString = connString;

connection.Open();

}

catch (System.Exception ex)

{

XtraMessageBox.Show(ex.Message, "操作数数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}

}

//关闭数据库链接

public static void CloseConnect()

{

try

{

connection.Close();

connection.Dispose();

}

catch (System.Exception ex)

{

XtraMessageBox.Show(ex.Message, "操作数数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}

}

public static bool ExitSearch(string str)

{

try

{

Connect();

SqlCommand command = new SqlCommand(str, connection);

SqlDataReader dr = command.ExecuteReader();

return dr.Read();

}

catch (System.Exception ex)

{

CloseConnect();

XtraMessageBox.Show(ex.Message, "操作数数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

throw ex;

}

finally

{

CloseConnect();

}

}

public static DataTable TableSearch(string str)

{

DataTable dt = new DataTable();

try

{

Connect();

SqlDataAdapter adp = new SqlDataAdapter(str, connection);

adp.Fill(dt);

return dt;

}

catch (System.Exception ex)

{

CloseConnect();

XtraMessageBox.Show(ex.Message, "操作数数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

throw ex;

}

finally

{

CloseConnect();

}

}

public static void SqlExecute(string str)

{

try

{

Connect();

SqlCommand command = new SqlCommand(str, connection);

command.ExecuteNonQuery();

}

catch (System.Exception ex)

{

CloseConnect();

XtraMessageBox.Show(ex.Message, "操作数数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

throw ex;

}

finally

{

CloseConnect();

}

}

public static int ExecuteRows(string str)

{

try

{

Connect();

SqlCommand command = new SqlCommand(str, connection);

int Rows = Convert.ToInt32(command.ExecuteScalar());

return Rows;

}

catch (System.Exception ex)

{

CloseConnect();

XtraMessageBox.Show(ex.Message, "操作数数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

throw ex;

}

finally

{

CloseConnect();

}

}

}

}

2.基于.net平台下的三层架构下的ASP.NET开发用的的数据库访问类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐