C#交互操作SqlServer数据库 基本的增删改查 增 using(SqlConnection conn=new SqlConnection("server=;database=;user=;pwd=")) { conn.Open(); using(SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText="Insert into T_user (Username,Password,Errotimes) values(@Username,@Password,@Errotimes)"; cmd.Parameters.Add(new SqlParameter("@Username",Username)); cmd.Parameters.Add(new SqlParameter("@Password",Password)); cmd.Parameters.Add(new SqlParameter("@Errotimes",Errotimes)); cmd.ExecuteNonQuery(); } } 删 using(SqlConnection conn=new SqlConnection("server=;database=;user=;pwd=")) { conn.Open(); using(SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText="delete from T_user where id=@id "; cmd.Parameters.Add(new SqlParameter("@id",id)); cmd.ExecuteNonQuery(); } } 改 using(SqlConnection conn=new SqlConnection("server=;database=;user=;pwd=")) { conn.Open(); using(SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText="Update _user set Username=@Username,Password=@Password,Errotimes=@Errotimes" cmd.Parameters.Add(new SqlParameter("@Username",Username)); cmd.Parameters.Add(new SqlParameter("@Password",Password)); cmd.Parameters.Add(new SqlParameter("@Errotimes",Errotimes)); cmd.ExecuteNonQuery(); } } 查询1 返回一行一列的查询 using(SqlConnection conn=new SqlConnection("server=;database=;user=;pwd=")) { conn.Open(); using(SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText="select count(*) from T_user where name=@name"; cmd.Parameters.Add(new SqlParameter("@name",name)); cmd.ExecuteScalar(); } } 查询2 “一般查询”(DataSet离线脱离数据库查询) using(SqlConnection conn=new SqlConnection("server=;database=;user=;pwd=")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select*from youdao where pwd=@pwd"; cmd.Parameters.Add(new SqlParameter("@pwd", txt.Text)); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dataset = new DataSet(); adapter.Fill(dataset); DataTable table = dataset.Tables[0]; DataRowCollection rows = table.Rows; for (int i = 0; i < rows.Count; i++) { DataRow row = rows[i]; int Age = (int)row["age"]; string name = (string)row["name"]; } } } 查询三 “大数据 ”连接数据库查询 ExcuteReader(); using(SqlConnection conn=new SqlConnection("server=;database=;user=;pwd=")) { conn.Open(); using(SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText="select*from T_user where name=@name"; cmd.Parameters.Add(new SqlParameter("@name",name)); using(SqlDataReader dr=cmd.ExecuteReader()) { while(dr.Read()) { string Name=dr.GetString(0); int Age =dr.GetInt32(1); } } } }