winform 常用的操作数据库的方法

using System.Data.SqlClient;

//用于select
private DataSet GetDataSet(string strsql)
{
	//硬编码
	string strcon = "server=IP,端口; uid=sa; pwd=test123; database=issyytv3_bbts";
	//读取配置文件
	//string strcon = ConfigurationManager.ConnectionStrings["conn"].ToString();
	SqlConnection con = new SqlConnection(strcon);
	DataSet ds = new DataSet();

	con.Open(); //打开数据库
	try
	{
		SqlDataAdapter DA = new SqlDataAdapter(strsql, con);
		DA.Fill(ds);
	}
	catch (SqlException E)
	{
		throw new Exception(E.Message);
	}
	con.Close();//关闭数据库

	return ds;
}
//用于insert 或 delete update
private int ExeSqlCmd(string strsql)
{
	string strcon = "server=IP,端口; uid=sa; pwd=test123; database=issyytv3_bbts";
	//string strcon = ConfigurationManager.ConnectionStrings["conn"].ToString();
	SqlConnection con = new SqlConnection(strcon);

	int RecordsAffected;

	con.Open(); //打开数据库
	try
	{
		SqlCommand sqlCmd = new SqlCommand(strsql, con);
		//影响的行数
		RecordsAffected = sqlCmd.ExecuteNonQuery();
	}
	catch (SqlException E)
	{
		throw new Exception(E.Message);
	}
	con.Close(); //关闭数据库

	return RecordsAffected;
}

用法举例:

string sqlVip = "select * from vip";
DataTable vipSet = GetDataSet(sqlVip).Tables[0];

//还可以判断一下结果的行数vipSet.Rows.Count
//或者直接读取某一行vipSet.Rows[0]

//遍历
foreach (DataRow dr in vipSet.Rows)
{
	string type_id = dr["type_id"].ToString();

	//更新
	string sqlUp = "update vip set acc_amt=100 where type_id='001'";
	ExeSqlCmd(sqlUp);
}

 

你可能感兴趣的:(sql,server)