2007

连接数据库
public static String connstr = "server=.;database=test2007;trusted_connection = true";
            


        public static DataTable ExecuteTable (String Sql,params SqlParameter [] ps)
        {
            using(SqlConnection conn = new SqlConnection(connstr))
            {
                SqlDataAdapter sda = new SqlDataAdapter(Sql, conn);


                sda.SelectCommand.Parameters.AddRange(ps);


                DataTable dt = new DataTable();


                sda.Fill(dt);


                return dt;
            }
        }


        public static int ExecuteNoquery(String Sql,params SqlParameter [] ps)
        {
            using(SqlConnection conn = new SqlConnection(connstr))
            {
                SqlCommand cmd = new SqlCommand(Sql, conn);
                cmd.Parameters.AddRange(ps);
                conn.Open();
                return cmd.ExecuteNonQuery();
                
            }
        }
}


查询并写入文件
if (textBox1.Text.Length<1)
            {
                MessageBox.Show("姓名不能为空");
                return;
            }
            DataTable dt = SqlHelper.ExecuteTable("select ENAME,OFFER,employee.DNO as DNO,DNAME,response from employee,department where employee.DNO = department.DNO and ENAME = @ENAME",new SqlParameter ("@ENAME",textBox1.Text));


            dataGridView1.DataSource=dt;






            if (dt.Rows.Count < 1)
            {
                MessageBox.Show("无相关信息");
            }


            WriteTxt(dt);


写入文件
     StreamWriter wr;


            if (File.Exists("aaa.txt"))
            {
                wr = File.AppendText("aaa.txt");
            }
            else
            {
                wr = File.CreateText("aaa.txt");
            }


            wr.WriteLine("姓名\t工资\t部门编号\t部门名字\t负责人");


            foreach (DataRow dr in dt.Rows)
            {
                wr.WriteLine(dr[0].ToString() + "\t" + dr[1].ToString() + "\t" + dr[2].ToString() + "\t" + dr[3].ToString() + "\t" + dr[4].ToString());
            }
            wr.Close();


增删
  private void button1_Click(object sender, EventArgs e)
        {        


            int rows=SqlHelper.ExecuteNoquery("insert into employee values(@A,@B,@C,@D)", new SqlParameter("@A",  textBox1.Text), new SqlParameter("@B", textBox2.Text), new SqlParameter("@C", textBox3.Text),new SqlParameter("@D",comboBox1.Text));


            if (rows >= 1)
            {
                MessageBox.Show("添加成功");
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            int rows = SqlHelper.ExecuteNoquery("delete from employee where ENO = @ENO", new SqlParameter("@ENO", textBox1.Text));


            if (rows >= 1)
            {
                MessageBox.Show("删除成功");
            }
        }

猜你喜欢

转载自blog.csdn.net/qq_28241239/article/details/79615768