日期:2014-05-18  浏览次数:20509 次

请问这段基础代码(数据库连接并读取记录)如何优化?
C# code
string conStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
        string sqlstr = "SELECT * FROM gameInfo where gameId=1";
        SqlConnection myConnection = new SqlConnection(conStr);
        SqlCommand myCommand = new SqlCommand(sqlstr, myConnection);
        myConnection.Open();


        SqlDataReader dr = myCommand.ExecuteReader();   //执行myCommand命令
        if (dr.Read())//如果能读到记录
        {
            labGameName.Text = dr["gameName"].ToString();
            labGamePutTime.Text = dr["gamePutTime"].ToString();
            labGameSize.Text = dr["gameSize"].ToString();
            labGameContent.Text = dr["gameDescription"].ToString();
            labGameOperate.Text = dr["gameOperate"].ToString();
            labGameType.Text = dr["gameType"].ToString();
            Image1.ImageUrl = dr["gamePic"].ToString();
            ImageGameCut1.ImageUrl = dr["gameCutPic1"].ToString();
            ImageGameCut2.ImageUrl = dr["gameCutPic2"].ToString();
            ImageGameCut3.ImageUrl = dr["gameCutPic3"].ToString();
            labRecommend.Text = dr["gameRecommend"].ToString();
        }
        dr.Close();

感觉自己的这段代码写的很糟糕,但不知道如何优化一下,应该用上USING语句吧,还有就是有很多重复的地方,应该进行怎么的优化,谢谢了

------解决方案--------------------
我已经很久没写过这种东西了,呵呵.平时用ORM工具.最少也用个SQLHelper一类的类操作.

LZ可以参考PETSHOP的 SQLHelper类,封装下
------解决方案--------------------
写的很好,最多后面加个dr.dispose();myconnection.dispose();
用using性能是一样的
string conStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
string sqlstr = "SELECT * FROM gameInfo where gameId=1";
using( SqlConnection myConnection = new SqlConnection(conStr))
{
using(SqlCommand myCommand = new SqlCommand(sqlstr, myConnection))
{
myConnection.Open();


using(SqlDataReader dr = myCommand.ExecuteReader()){ //执行myCommand命令
if (dr.Read())//如果能读到记录
{
labGameName.Text = dr["gameName"].ToString();
labGamePutTime.Text = dr["gamePutTime"].ToString();
labGameSize.Text = dr["gameSize"].ToString();
labGameContent.Text = dr["gameDescription"].ToString();
labGameOperate.Text = dr["gameOperate"].ToString();
labGameType.Text = dr["gameType"].ToString();
Image1.ImageUrl = dr["gamePic"].ToString();
ImageGameCut1.ImageUrl = dr["gameCutPic1"].ToString();
ImageGameCut2.ImageUrl = dr["gameCutPic2"].ToString();
ImageGameCut3.ImageUrl = dr["gameCutPic3"].ToString();
labRecommend.Text = dr["gameRecommend"].ToString();
}
}

}
}
------解决方案--------------------
把SELECT * FROM 改了

改成 SELECT [你需要的字段] FROM

即使需要该表的全部字段

请写上列名
------解决方案--------------------
string conStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
string sqlstr = "SELECT * FROM gameInfo where gameId=1";
SqlConnection myConnection = new SqlConnection(conStr);
SqlCommand myCommand = new SqlCommand(sqlstr, myConnection);
myConnection.Open();


using( SqlDataReader dr = myCommand.ExecuteReader())
{ //执行myCommand命令
while (dr.Read())//如果能读到记录
{
labGameName.Text = dr.getstring(0);