这是我在C#下第一次写的一个函数对数据库的操作,请高手指点!Knight94(愚翁) 等,谢谢!
由于很多东西不太清楚,比如在对数据库连接的释放、数据集关闭等,想请高手具体指导以下代码中不妥或错误的地方!**标示的是我认为重点模糊的地方。谢谢!
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;
}
}
//****在一般情况下是这样来关闭数据库的连接,和数据集的?
可能比较乱,请大家帮帮忙!谢谢!