日期:2014-05-16  浏览次数:20414 次

如何将GridView中的数据导入到数据库

需求:将Gridview中的数据直接导入到数据苦中对应的学科表中.

界面:导入到总表:

protected void btnExportToMaster_Click(object sender, EventArgs e)
        {
            //连接字串"sqlConnString" 
            string sqlConnString = "";
            sqlConnString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconn"].ToString();
            SqlConnection con = new SqlConnection(sqlConnString);
            con.Open();
            //配置文件读取examID
            string examID = System.Configuration.ConfigurationManager.AppSettings["examID"];
            //根据examID考试号决定汇总到对应科目的表中
            string tbName = System.Configuration.ConfigurationManager.AppSettings[examID];
            //事物
            SqlTransaction tran = con.BeginTransaction();
            try
            {
                for (int i = 0; i < GVScore.Rows.Count; i++)
                {
                    string sqlStr = "";
                    SqlCommand comm = new SqlCommand(sqlStr, con);
                    string strExamId = GVScore.Rows[i].Cells[1].Text.Trim().ToString();

                    //获取HyperLink1中StudentId值
                    HyperLink href = (HyperLink)GVScore.Rows[i].Cells[2].FindControl("HyperLink1");
                    string strStudentId = href.Text;
                     

                    //如果是超链接只能获取空字符串
                    //HyperLink hl=(HyperLink)GVScore.FindControl ("HyperLink1");
                    //string strStudentId = hl.Text.ToString (); 

                    string strStudentName = GVScore.Rows[i].Cells[3].Text.Trim().ToString();
                    string  StudentScore = GVScore.Rows[i].Cells[4].Text.Trim().ToString();

                    sqlStr = "INSERT  " + tbName + "(examId,StudentName,StudentId,StudentScore) VALUES ('" + strExamId + "','" + strStudentId  + "','" + strStudentName + "','"+StudentScore +"')";

                    comm.CommandText = sqlStr;
                    comm.Connection = con;
                    comm.Transaction = tran;
                    comm.ExecuteNonQuery();
                }
                tran.Commit();
                Response.Write("<script>alert('导入成功!请勿重复导入!');</script>");
            }
            catch (Exception ex)
            {
                Response.Write("更新失败,失败原因:" + ex.Message);
                tran.Rollback();//事务回滚
            }
            finally
            {
                con.Close();
            }
        }


配置文件:

	  <!--考试号-->
    <!--43表示VB-->
	  <add key="examId" value="43"/>
    <!--考试号对应的总表-->
    <add key ="43" value="t_VB_ALLStudent_Scores"/>


界面执行结果:

数据库执行结果: