日期:2014-05-18 浏览次数:21144 次
<add name="SQLConnString1" connectionString="server=(local);database=EpgInfo;user id=sa;password=sa;integrated security=SSPI;min pool size=4;max pool size=4;" providerName="System.Data.SqlClient"/>
------解决方案--------------------
数据库连接及访问常用几个对象和方法
class DataConn {
#region 建立数据库连接
/// <summary>
/// 建立数据库连接.
/// </summary>
/// <returns>返回SqlConnection对象</returns>
public SqlConnection getcon()
{
string M_str_sqlcon = "Data Source=MIAMI;Initial Catalog=db_crm;Integrated Security=SSPI;";
SqlConnection myCon = new SqlConnection(M_str_sqlcon);
return myCon;
}
#endregion
#region 执行SqlCommand命令
/// <summary>
/// 执行SqlCommand
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
public void getcom(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);
sqlcom.ExecuteNonQuery();
sqlcom.Dispose();
sqlcon.Close();
sqlcon.Dispose();
}
#endregion
#region 创建DataSet对象
/// <summary>
/// 创建一个DataSet对象
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
/// <param name="M_str_table">表名</param>
/// <returns>返回DataSet对象</returns>
public DataSet getds(string M_str_sqlstr, string M_str_table)
{
SqlConnection sqlcon = this.getcon();
SqlDataAdapter sqlda = new SqlDataAdapter(M_str_sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlda.Fill(myds, M_str_table);
return myds;
}
#endregion
#region 创建SqlDataReader对象
/// <summary>
/// 创建一个SqlDataReader对象
/// </summary>
/// <param name="M_str_sqlstr">SQL语句</param>
/// <returns>返回SqlDataReader对象</returns>
public SqlDataReader getread(string M_str_sqlstr)
{
SqlConnection sqlcon = this.getcon();
SqlCommand sqlcom = new SqlCommand(M_str_sqlstr, sqlcon);
sqlcon.Open();
SqlDataReader sqlread = sqlcom.ExecuteReader(CommandBehavior.CloseConnection);
return sqlread;
}
#endregion
}
用这个类的实例的方法来实现各种sql操作就可以啦
举例,登录按钮:
private void btnLogin_Click(object sender, EventArgs e)
{
SqlDataReader sqlread = boperate.getread("select UserName,UserPwd from tb_User where UserName='" + cboxUName.Text.Trim() + "' and UserPwd='" + txtPwd.Text.Trim() + "'");
sqlread.Read();
if (sqlread.HasRows)
{
M_str_name = cboxUName.Text;
M_str_pwd = txtPwd.Text.Trim();
frmMain fmain = new frmMain();
this.Hide();