今天的收获

今天学习了using(SqlConnection cnn = new ...)

{

}

使用这个方法可以不用使用dispopse()释放资源,也可以不用关闭连接

ADO.NET Transaction的使用包括以下几个步骤:

1.     建立数据库联接.

2.     依据数据库联接创建事务

3.     执行语句

4.     提交或回滚事物

SqlTransaction trans = sqlcnn.BeginTransaction();//为事物创建对象

  sqlcmm.Transaction = trans;  //为命令对象指定事物对象

trans.Commit();  //提交事物

trans.Rollback();  //回滚事物

导入txt文档信息

protected void Button1_Click(object sender, EventArgs e)
    {
        string strfile = Server.MapPath("~/" + "user.txt");
        this.FileUpload1.SaveAs(strfile);
        FileStream fs = new FileStream(strfile,FileMode.Open);
        StreamReader sr = new StreamReader(fs);

        string str = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
        using(SqlConnection sqlcnn=new SqlConnection(str))
        {
            SqlCommand sqlcmm = new SqlCommand();
            sqlcmm.Connection = sqlcnn;
            sqlcmm.CommandText = "insert into users(uid,name,power) values(@uid,@name,@power)";
            SqlParameter param1 = new SqlParameter("@uid",System.Data.SqlDbType.VarChar, 6);
            sqlcmm.Parameters.Add(param1);

            SqlParameter param2 = new SqlParameter("@name",System.Data.SqlDbType.NVarChar, 8);
            sqlcmm.Parameters.Add(param2);

            SqlParameter param3 = new SqlParameter("@power", DropDownList1.SelectedValue);
            sqlcmm.Parameters.Add(param3);

            string line = sr.ReadLine();
            string[] items = null;
            sqlcnn.Open();
            while (line!=null)
            {
                items = line.Split(';');
                param1.Value = items[0];
                param2.Value = items[1];
                switch (items[2])
                {
                    case "管理员":
                        param3.Value = 0;
                        break;
                    case "售票员":
                        param3.Value = 1;
                        break;
                    case "检票员":
                        param3.Value = 2;
                        break;
                }
                sqlcmm.ExecuteNonQuery();
                line = sr.ReadLine();
            }
            Response.Write("OK");
        }
        sr.Close();
        fs.Close();
    }


你可能感兴趣的:(数据库,String,object,null,insert,button)