嗯,剛剛嘗試了幾種往資料庫插入資料的方式,記錄一下:
這裡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,超級簡單吧,哦是菜鳥~~~じゃあ、一緒に頑張ろう!