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

嗯,刚刚尝试了几种往数据库插入数据的方式,记录一下:
这里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,超级简单吧,哦是菜鸟~~~じゃあ、一緒に頑張ろう!

posted @ 2008-05-06 16:36  小牛大牛  阅读(681)  评论(0编辑  收藏  举报
咱这社会,努力不一定会有回报,但要是不努力,您可就得空虚.您说这讨老婆,生孩子,买房子,购车子,哪样不得自己动手,别人动手咱也不能放心啊,您说是不是这么个理儿?....