尝试了几种往数据库插入数据的方式

嗯,刚刚尝试了几种往数据库插入数据的方式,记录一下:
这里aspx页面上有两个 TextBox控件,名称分别为userName 和 pwd.还有一个submit按钮,以下代码都是写在按钮的时间中的:(截图如下)

1.直接用 SqlCommand写sql语句:
          String strusername  =   this .userName.Text;
        String strpwd 
=   this .pwd.Text;         

          SqlConnection conn 
=   new  SqlConnection();
        SqlCommand comm 
=   new  SqlCommand();
       

        conn 
=   new  SqlConnection( " server=localhost;database=demo;uid=sa;pwd=123456 " );
        conn.Open();
        comm.Connection 
=  conn;
        comm.CommandText 
=   " insert into demo(username,pwd) values(' "   +  strusername  +   " ',' "   +  strpwd  +   " ') " ;
        comm.ExecuteNonQuery();

2.用 SqlDataAdapter和DataTable:
        SqlConnection conn  =   new  SqlConnection();
        SqlCommand comm 
=   new  SqlCommand();
        SqlDataAdapter dataAdapter 
=   new  SqlDataAdapter();
        
          String strusername 
=   this .userName.Text;
        String strpwd 
=   this .pwd.Text;

        conn 
=   new  SqlConnection( " server=localhost;database=demo;uid=sa;pwd=123456 " );
        conn.Open();
        comm 
=   new  SqlCommand( " select * from demo " , conn);
        dataAdapter.SelectCommand 
=  comm;
        dataAdapter.InsertCommand 
=   new  SqlCommandBuilder(dataAdapter).GetInsertCommand();
        DataTable dataTable 
=   new  DataTable();
        dataAdapter.Fill(dataTable);
        DataRow dataRow 
=  dataTable.NewRow();
        dataRow[
1 =  strusername;
        dataRow[
2 =  strpwd;
        dataTable.Rows.Add(dataRow);
        dataAdapter.Update(dataTable);

3.用 SqlDataAdapter和DataSet:
        SqlConnection conn  =   new  SqlConnection();
        SqlCommand comm 
=   new  SqlCommand();
        SqlDataAdapter dataAdapter 
=   new  SqlDataAdapter();

        String strusername 
=   this .userName.Text;
        String strpwd 
=   this .pwd.Text;

        conn 
=   new  SqlConnection( " server=localhost;database=demo;uid=sa;pwd=123456 " );
        conn.Open();
        comm 
=   new  SqlCommand( " select * from demo " , conn);
        dataAdapter.SelectCommand 
=  comm;
        dataAdapter.InsertCommand 
=   new  SqlCommandBuilder(dataAdapter).GetInsertCommand();
        dataAdapter.Fill(dataSet);
        DataRow dataRow 
=  dataSet.Tables[ 0 ].NewRow();
        dataRow[
1 =  strusername;
        dataRow[
2 =  strpwd;
        dataSet.Tables[
0 ].Rows.Add(dataRow);
        dataAdapter.Update(dataSet);

OK,超级简单吧,哦是菜鸟~~~じゃあ、一緒に頑張ろう!

转载于:https://www.cnblogs.com/gugunet/archive/2008/05/06/1185372.html

你可能感兴趣的:(尝试了几种往数据库插入数据的方式)