程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#在winform中操作數據庫,實現數據增刪改查,

C#在winform中操作數據庫,實現數據增刪改查,

編輯:C#入門知識

C#在winform中操作數據庫,實現數據增刪改查,


1.前言:

運行環境:VS2013+SQL2008+Windows10

程序界面預覽:

使用的主要控件:dataGridview和menuStrip等。

 

2.功能具體介紹:

1.首先,我們要先實現基本的數據操作,增刪改查這幾個操作。

(1)先定義一個數據庫操作的公共類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Security.Cryptography;

namespace Data
{
    class SqlDesigner
    {
        private static string connStr = ConfigurationManager.ConnectionStrings["data"].ConnectionString;
        /// <summary>
        /// 返回受影響的數據行數
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int ExecuteNoQuery(string sql)
        {
            using (SqlConnection conn=new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd=conn.CreateCommand())
                {
                  cmd.CommandText = sql;
                  return cmd.ExecuteNonQuery();
                  
                }
            }
        }
        /// <summary>
        /// 返回一個數據集
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static DataSet ExecuteDataSet(string sql)
        {
            using (SqlConnection xonn=new SqlConnection(connStr))
            {
                xonn.Open();
                using (SqlCommand cmd = xonn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataSet dataset = new DataSet();
                    adapter.Fill(dataset);
                    return dataset;
                }
            }
        }
        public static object ExecuteScalar(string sql)
        {
            using (SqlConnection conn=new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd=conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    return cmd.ExecuteScalar();
                }
            }
        }
        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="strPwd"></param>
        /// <returns></returns>
        public static string GetMD5(string strPwd)
        {
            string pwd = "";
            //實例化一個md5對象
            MD5 md5 = MD5.Create();
            // 加密後是一個字節類型的數組
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(strPwd));
            //翻轉生成的MD5碼        
            s.Reverse();
            //通過使用循環,將字節類型的數組轉換為字符串,此字符串是常規字符格式化所得
            //只取MD5碼的一部分,這樣惡意訪問者無法知道取的是哪幾位
            for (int i = 3; i < s.Length - 1; i++)
            {
                //將得到的字符串使用十六進制類型格式。格式後的字符是小寫的字母,如果使用大寫(X)則格式後的字符是大寫字符
                //進一步對生成的MD5碼做一些改造
                pwd = pwd + (s[i] < 198 ? s[i] + 28 : s[i]).ToString("X");
            }
            return pwd;
        }
    
    }
}
數據庫操作公共類

(2)運用建立的公共類,進行數據庫的操作:

  a.數據查詢:
ds = SqlDesigner.ExecuteDataSet("select * from dtuser");            
dt = ds.Tables[0];            
dataGridView1.DataSource = dt;
  b.數據添加
 i = SqlDesigner.ExecuteNoQuery("insert into dtuser(uid,uname,pwd,uflag)values('" + textBox1.Text + "','" + textBox2.Text + "','" +textBox3.Text+ "','" + textBox4.Text + "')");
  c.數據刪除
string currentIndex = dataGridView1.CurrentRow.Cells[0].Value.ToString();
i = SqlDesigner.ExecuteNoQuery("delete from dtuser where uid='" + currentIndex + "'");
  d.數據修改
i = SqlDesigner.ExecuteNoQuery("update dtrole set rname='" + textBox2.Text + "',flag='" + textBox3.Text + "'where rid='" + textBox1.Text + "'");
  e.一些細節

  這裡,我們修改一下添加數據,讓添加的數據變成字符串的形式,也就是加密操作:

string str = SqlDesigner.GetMD5(textBox3.Text.Trim());                
 i = SqlDesigner.ExecuteNoQuery("insert into dtuser(uid,uname,pwd,uflag)values('" + textBox1.Text + "','" + textBox2.Text + "','" + str + "','" + textBox4.Text + "')");

 

(3)dataGridView控件:

//綁定數據源
dataGridView1.DataSource = dt;
//自動適應列寬
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

3.代碼僅供參考:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Data
{
    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();            
        }                   
                
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();

        private void TextBoxNull()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
        }
        private void 用戶ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TextBoxNull();
            ds = SqlDesigner.ExecuteDataSet("select * from dtuser");            
            dt = ds.Tables[0];
            dataGridView1.DataSource = dt;
            labelshow();
        }

        private void 角色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TextBoxNull();
            ds = SqlDesigner.ExecuteDataSet("select *from dtrole");
            dt = ds.Tables[0];
            dataGridView1.DataSource = dt;
            label4.Text = "None";
            textBox4.Text = "None";
            labelshow();
        }

        private void 對象ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TextBoxNull();
            ds = SqlDesigner.ExecuteDataSet("select * from dtfunction");
            dt = ds.Tables[0];
            dataGridView1.DataSource = dt;
            labelshow();
        }

        private void 幫助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TextBoxNull();
            ds = SqlDesigner.ExecuteDataSet("select * from help");
            dt = ds.Tables[0];
            dataGridView1.DataSource = dt;
            dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
        }
        //雙擊dataGridView1
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string index = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            if (label1.Text == "uid")
            {
                ds = SqlDesigner.ExecuteDataSet("select *from dtuser where uid='" + index + "'");
                dt = ds.Tables[0];
                DataRow row = dt.Rows[0];
                textBox1.Text = row["uid"].ToString();
                textBox2.Text = row["uname"].ToString();
                textBox3.Text = row["pwd"].ToString();
                textBox4.Text = row["uflag"].ToString();
            }
            if (label1.Text == "rid")
            {
                ds = SqlDesigner.ExecuteDataSet("select *from dtrole where rid='" + index + "'");
                dt = ds.Tables[0];
                DataRow row = dt.Rows[0];
                textBox1.Text = row["rid"].ToString();
                textBox2.Text = row["rname"].ToString();
                textBox3.Text = row["flag"].ToString();
                textBox4.Text = "None";
            }
            if (label1.Text == "fid")
            {
                ds = SqlDesigner.ExecuteDataSet("select *from dtfunction where fid='" + index + "'");
                dt = ds.Tables[0];
                DataRow row = dt.Rows[0];
                textBox1.Text = row["fid"].ToString();
                textBox2.Text = row["fname"].ToString();
                textBox3.Text = row["flag"].ToString();
                textBox4.Text = row["uflag"].ToString();
            }
        }
        private void labelshow() 
        {
            label1.Text = dataGridView1.Columns[0].HeaderText;
            label2.Text = dataGridView1.Columns[1].HeaderText;
            label3.Text = dataGridView1.Columns[2].HeaderText;
            try
            {
                label4.Text = dataGridView1.Columns[3].HeaderText;
            }
            catch (Exception)
            {

                label4.Text = "None";
            }                                                         
        }               
        private void btn_add_Click(object sender, EventArgs e)
        {            
            int i = 0;
            if (label1.Text=="uid")
            {
                string str = SqlDesigner.GetMD5(textBox3.Text.Trim());                
                i = SqlDesigner.ExecuteNoQuery("insert into dtuser(uid,uname,pwd,uflag)values('" + textBox1.Text + "','" + textBox2.Text + "','" + str + "','" + textBox4.Text + "')");
            }
            else if (label1.Text == "rid")
            {                
                i = SqlDesigner.ExecuteNoQuery("insert into dtrole(rid,rname,flag)values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')");
            }
            else
            {
                try
                {
                    i = SqlDesigner.ExecuteNoQuery("insert into dtfunction(fid,rid,uid,uflag)values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')");
                }
                catch (Exception)
                {
                    MessageBox.Show("添加失敗");
                }
                
            }
            
            if (i > 0)
            {
                MessageBox.Show("添加成功");
            }
            else
            {
                MessageBox.Show("添加失敗");
            }                                        
        }
        
        private void btn_del_Click(object sender, EventArgs e)
        {
            int i = 0;
            string currentIndex = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            if (label1.Text=="uid")
            {
                i = SqlDesigner.ExecuteNoQuery("delete from dtuser where uid='" + currentIndex + "'");
            }
            else if (label1.Text=="fid")
            {
                i = SqlDesigner.ExecuteNoQuery("delete from dtfunction where fid='" + currentIndex + "'");
            }
            else
            {
                i = SqlDesigner.ExecuteNoQuery("delete from dtrole where rid='" + currentIndex + "'");
            }
            if (i > 0)
            {
                MessageBox.Show("刪除成功");
            }
            else
            {
                MessageBox.Show("刪除失敗");
            }
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            int i = 0;
            if (label1.Text == "rid")
            {
                i = SqlDesigner.ExecuteNoQuery("update dtrole set rname='" + textBox2.Text + "',flag='" + textBox3.Text + "'where rid='" + textBox1.Text + "'");
            }
            if (label1.Text == "uid")
            {
                i = SqlDesigner.ExecuteNoQuery("update dtuser set uname='" + textBox2.Text + "',pwd='" + textBox3.Text + "',uflag='" + textBox4.Text + "'where uid='" + textBox1.Text + "'");
            }
            if (label1.Text=="fid")
            {
                i = SqlDesigner.ExecuteNoQuery("update dtfunction set rid='" + textBox2.Text + "',uid='" + textBox3.Text + "',uflag='" + textBox4.Text + "'where fid='" + textBox1.Text + "'");
            }
            if (i > 0)
            {
                MessageBox.Show("Succeed!");
            }
            else
            {
                MessageBox.Show("Failed!");
            }
        }

        

       
        
    }
}
View All Code

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved