双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

这是我在C#下第一次写的一个函数对数据库的操作,请高手指点!Knight94(愚翁) 等,谢谢!

vigrous_chen vigrous_chen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
由于很多东西不太清楚,比如在对数据库连接的释放、数据集关闭等,想请高手具体指导以下代码中不妥或错误的地方!**标示的是我认为重点模糊的地方。谢谢!
public string BuildDJH(string ZTH,string bh,string T_name,string DHZF)
{
string s_Sql,str;
int FirstValue,NewValue,I;
//定义一些有关数据操作的变量
DateTime dt=DateTime.Now;
bh=bh+dt.ToString("yyyyMM");
SqlConnection thisconnection=new SqlConnection(@"Data Source=127.0.0.1\logistics;"
+"persist security info=False;"
+"user id=sa;password=;Initial Catalog=wlgl");
//打开连接
thisconnection.Open();
SqlDataAdapter thisAdapter=new SqlDataAdapter("select count ("+DHZF+") from "+T_name
+" where ZTH='"+ZTH+"' And "+DHZF+" like'"+bh+"%'",thisconnection);
SqlCommandBuilder thisBuilder=new SqlCommandBuilder (thisAdapter);
DataSet thisDataSet=new DataSet();
thisAdapter.Fill(thisDataSet,"JLSL");
I=thisDataSet.Tables["JLSL"].Rows.Count;
if (I<=0)
//**是否要关闭连接呢?还需要关闭其它的吗?
{ thisconnection.Close();
return bh+"0001";
}
else
//*****在这里我是另外生成的一个SqlDataAdapter,有没有必要,可否用上面的
// thisAdapter,假如用或不用上面的合理的写法是这样的?
{SqlDataAdapter otherAdapter=new SqlDataAdapter("select "+DHZF+" as DJH from "+T_name
+" where ZTH='"+ZTH+"' And "+DHZF+" like'"+bh+"%' order by "+DHZF,thisconnection);
//***同样我也是另外生成的,问题和上面类似
SqlCommandBuilder otherBuilder=new SqlCommandBuilder(otherAdapter);
//***同样我也是另外生成的,问题和上面类似

DataSet otherDataSet=new DataSet();
otherAdapter.Fill(otherDataSet,"DJH");
I=otherDataSet.Tables["DJH"].Rows.Count;
str=otherDataSet.Tables["DJH"].Rows[I-1]["DJH"].ToString().Trim();
str=str.Substring(8,4);
FirstValue=Convert.ToInt32(str);
if (FirstValue<=0)
{ thisconnection.Close();
return bh+"0001";
}
else
{ NewValue=FirstValue+10001;
str=Convert.ToString(NewValue);
str=str.Substring(1,4);
thisconnection.Close();
return bh+str;
}
}
//****在一般情况下是这样来关闭数据库的连接,和数据集的?
可能比较乱,请大家帮帮忙!谢谢!

...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
vigrous_chen
C# 111,129 成员 642,540 内容