三、附赠一个很有用的类DBHelper类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace TestDBHelper
{
class DBHelper
{
/// <summary>
/// 连接数据库的地址
/// </summary>
private const string CONNECTIONSTR = "";
/// <summary>
/// 获得连接
/// </summary>
/// <returns></returns>
public static SqlConnection GetConnection()
{
return new SqlConnection(CONNECTIONSTR);
}
/// <summary>
/// 执行增删改操作
/// </summary>
/// <param name="sql">执行的sql语句</param>
/// <returns>返回受影响的行数</returns>
public static int ExecuteNonQuery(string sql)
{
SqlConnection con = GetConnection();
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
int ret = cmd.ExecuteNonQuery();
con.Close();
return ret;
}
/// <summary>
/// 执行查询操作
/// </summary>
/// <param name="sql">执行的sql语句</param>
/// <returns>返回查询结果的首行首列对象</returns>
public static Object ExecuteScalar(string sql)
{
SqlConnection con = GetConnection();
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
Object obj = cmd.ExecuteScalar();
con.Close();
return obj;
}
/// <summary>
/// 执行查询操作
/// </summary>
/// <param name="sql">执行的sql语句</param>
/// <returns>返回一张查询表SqlDataReader对象</returns>
public static SqlDataReader ExecuteReader(String sql)
{
SqlConnection con = GetConnection();
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
/// <summary>
/// 获得临时数据表的方法
/// </summary>
/// <param name="sql">执行的sql语句</param>
/// <returns>返回一张创建的临时表</returns>
public static DataTable GetDataTable(string sql)
{
SqlConnection con = GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter(sql, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}
}
|