在用c#写关于Windows Form程序时,对数据库的操作是最基本的,对这些操作作了一些整理 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace StudentSys { class StudentS { //连接字符串 public static string connectionString = "Data Source=.;Initial Catalog=student;Integrated Security=True"; /// <summary> /// 查询所有的记录,在窗体加载时显示 /// </summary> /// <param name="sql">查询语句</param> /// <returns></returns> public static DataSet DataSetD(string sql) { using (SqlConnection conn = new SqlConnection(connectionString)) { SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataSet ds = new DataSet(); sda.Fill(ds); return ds; } } /// <summary> /// 执行相应的SQL语句 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static int ExcuteQuery(string sql) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; int i = cmd.ExecuteNonQuery(); return i; } } /// <summary> /// 删除数据库中相应的记录 /// </summary> /// <param name="sql"></param> public static void DeleteD(string sql) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } /// <summary> /// 在添加记录时,检查数据库中是否有相同的记录 /// </summary> /// <param name="sql"></param> /// <returns>返回数据库中已经存在的记录的条数</returns> public static int SelectDS(string sql) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); object obj; int i = 0; cmd.CommandText = sql; obj = cmd.ExecuteScalar(); i = (int)obj; //记录相同ID的记录的条数 return i; } } /// <summary> /// 修改记录 /// </summary> /// <param name="sql"></param> public static void UpdateD(string sql) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } } } 还有其他的一些方法,这些是比较简单的!!!