C#+Access 员工信息管理--简单的增删改查操作和.ini配置文件的读写操作。

2022/4/13 14:13:19

本文主要是介绍C#+Access 员工信息管理--简单的增删改查操作和.ini配置文件的读写操作。,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.本程序的使用的语言是C#,数据库是Access2003。主要是对员工信息进行简单的增删改查操作和对.ini配置文件的读写操作。
2.代码运行效果如下:


功能比较简单。其中在得到查询结果后,在查询结果界面上最上面的一行数字好像是根据数据库的列数自动获取到的,我本想把它删掉来着,但是没成功。
3.代码实现

点击查看代码。clsDbOperate类--主要是数据库连接和员工的增删改查操作。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UserInfoManage
{
    public class clsDbOperate {
        static string exePath = System.Environment.CurrentDirectory + "\\Data\\";//数据库在本程序中所在路径
        static string Psd = "PTC8800";

        OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;data source=" + exePath + "SystemData.mdb;" + "Jet OLEDB:Database Password=" + Psd);
        OleDbCommand oleCommand = new OleDbCommand();//操作查询

        private OleDbDataReader ole_reader = null;
        private DataTable dt = null;

        public DataTable dtSelectResult(string sql) {
            DataTable dt = new DataTable(); //新建表对象
            try {
                conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //创建适配对象
                da.Fill(dt); //用适配对象填充表对象
                conn.Close();
            } catch (Exception) {
            } finally {
                conn.Close();
            }
            return dt;
        }
        public int intSelectResultCount(string sql) {
            DataSet ds = new DataSet(); //新建表对象
            int n = 0;
            try {
                conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //创建适配对象

                da.Fill(ds); //用适配对象填充表对象
                n = ds.Tables[0].Rows.Count;
            } catch (Exception) {
            } finally {
                conn.Close();
            }
            return n;
        }
        public int Del_Ins_Upd_Result(string sql) {
            int n = 0;
            try {
                conn.Open();
                //增
                //string sql = "insert into 表名(字段1,字段2,字段3,字段4)values(...)";
                //删 
                //string sql = "delete from 表名 where ="...; 
                //改 
                //string sql = "update student set 字段1=" ...; 
                OleDbCommand comm = new OleDbCommand(sql, conn);
                n = comm.ExecuteNonQuery();//执行sql语句
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            } finally {
                conn.Close();
            }
            conn.Close();
            return n;
        }
        /// <summary>
        /// 从数据库里面获取数据
        /// </summary>
        ///<param name="strSql">查询语句
        /// <returns>数据列表</returns>
        public DataTable GetDataTableFromDB(string strSql) {
            if (exePath == null) {
                return null;
            }
            try {
                conn.Open();//打开连接
                if (conn.State == ConnectionState.Closed) {
                    return null;
                }
                oleCommand.CommandText = strSql;
                oleCommand.Connection = conn;
                ole_reader = oleCommand.ExecuteReader(CommandBehavior.Default);
                dt = ConvertOleDbReaderToDataTable(ref ole_reader);
                ole_reader.Close();
                ole_reader.Dispose();
            } catch (System.Exception e) {
                //Console.WriteLine(e.ToString());
                MessageBox.Show(e.Message);
            } finally {
                if (conn.State != ConnectionState.Closed) {
                    conn.Close();
                }
            }
            return dt;
        }
        /// <summary>
        /// 转换数据格式
        /// </summary>
        ///<param name="reader">数据源
        /// <returns>数据列表</returns>
        private DataTable ConvertOleDbReaderToDataTable(ref OleDbDataReader reader) {
            DataTable dtTab = null;
            DataRow dr = null;
            int dataColumnCount = 0;
            int i = 0;
            dataColumnCount = reader.FieldCount;
            dtTab = BuildAndInitDataTable(dataColumnCount);
            dtTab.Rows.Add("序号", "工号", "姓名", "密码", "是否管理员", "登录次数");
            if (dtTab == null) {
                return null;
            }
            while (reader.Read()) {             
                dr = dtTab.NewRow();
                             
                for (i = 0; i < dataColumnCount; ++i) {
                    dr[i] = reader[i];
                }
                dtTab.Rows.Add(dr);
            }
            return dtTab;
        }
        /// <summary>
        /// 创建并初始化数据列表
        /// </summary>
        ///<param name="fieldCount">列的个数
        /// <returns>数据列表</returns>
        private DataTable BuildAndInitDataTable(int fieldCount) {
            DataTable dtTab = null;
            DataColumn dc = null;
            int i = 0;
            if (fieldCount <= 0) {
                return null;
            }
            dtTab = new DataTable();
            for (i = 0; i < fieldCount; ++i) {
                dc = new DataColumn(i.ToString());
                dtTab.Columns.Add(dc);
            }
            return dtTab;
        }
    }
}

点击查看代码。FileOperation类--.ini配置文件的操作类。主要是对FileConfig.ini文件进行读写操作
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace UserInfoManage
{
    public class FileOperation {
        /// <summary>
        /// 写入INI文件
        /// </summary>
        /// <param name="section">节点名称[如[TypeName]]</param>
        /// <param name="key">键</param>
        /// <param name="val">值</param>
        /// <param name="filepath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="section">节点名称</param>
        /// <param name="key">键</param>
        /// <param name="def">值</param>
        /// <param name="retval">stringbulider对象</param>
        /// <param name="size">字节大小</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
        private string strSec = ""; //INI文件名

        public string ReadFile(string strFilePath, string FieldName) {
            string returnName = null;
            if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
            {
                //strSec = Path.GetFileNameWithoutExtension(strFilePath);
                strSec = "Information";
                returnName = ContentValue(strFilePath, strSec, FieldName);
            } else {
                //MessageBox.Show("INI文件不存在");
            }
            return returnName;
        }

        public int WriteFile(string strFilePath, string FieldName, string FieldValue) {
            int ret = 0;
            try {
                //根据INI文件名设置要写入INI文件的节点名称
                //此处的节点名称完全可以根据实际需要进行配置
                //strSec = Path.GetFileNameWithoutExtension(strFilePath);  //获取INI文件的节点名称
                strSec = "Information";
                WritePrivateProfileString(strSec, FieldName, FieldValue.Trim(), strFilePath);
                ret = -1;
                //MessageBox.Show("写入成功");
            } catch (Exception) {
            }
            return ret;
        }

        private string ContentValue(string strFilePath, string Section, string key)           //自定义函数
        {
            StringBuilder temp = new StringBuilder(1024);
            GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
            //对应定义的读取函数,返回值
            return temp.ToString();
        }
    }
}

点击查看代码。FrmUserManager类--界面类。主要是对用户的信息进行操作
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UserInfoManage;
using UserInfoManage.from;
using System.Runtime.InteropServices;

namespace UserInfoManage {
    public partial class FrmUserManager : Form {
        private clsDbOperate dbOperate;
        private FileOperation fileOperation;
        private string strUserId;
        private string strUserName;
        private string strPassword;
        private string strFilePath = Application.StartupPath + @"\FileConfig.ini";//定义INI文件的路径

        public FrmUserManager() {
            InitializeComponent();
        }
        private void FrmUserManager_Load(object sender, EventArgs e) {
            dbOperate = new clsDbOperate();
            RefreshUserInfo();
            dgvUserInfo.AllowUserToAddRows = false;
            dgvUserInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//设置为整行被选中
            dgvUserInfo.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            dgvUserInfo.BackgroundColor = Color.White;
            dgvUserInfo.ReadOnly = true;
            dgvUserInfo.Columns[0].HeaderText = "序号";            
            dgvUserInfo.Columns[1].HeaderText = "工号";
            dgvUserInfo.Columns[2].HeaderText = "姓名";
            dgvUserInfo.Columns[3].HeaderText = "密码";
            dgvUserInfo.Columns[4].HeaderText = "是否管理员";
            dgvUserInfo.Columns[5].HeaderText = "登录次数";

            fileOperation = new FileOperation();
        }       
        /// <summary>
        /// 增加操作
        /// </summary>
        private void btnAddUserInfo_Click(object sender, EventArgs e) {
            if (txtUserID.Text == "" || txtUserName.Text == "" || txtUserPsd.Text == "") {
                MessageBox.Show("员工信息不完整,无法添加!带*为必填项", "提示", MessageBoxButtons.OK);
            } else {
                string sql = string.Empty;
                string strIsAdmin = string.Empty;
                strIsAdmin = chkIsAdmin.Checked == true ? "1" : "0";
                try {
                    sql = "select UserName from userInfo where UserID='" + txtUserID.Text + "'";
                    if (dbOperate.intSelectResultCount(sql) > 0) {
                        MessageBox.Show("已存在的员工工号!", "提示", MessageBoxButtons.OK);
                        return;
                    } else {
                        sql = "insert into userInfo(UserID,UserName,UserPsd,IsAdmin,LoginTimes)";
                        sql += "Values('" + txtUserID.Text + "','" + txtUserName.Text + "','" + txtUserPsd.Text + "','" + strIsAdmin + "',0)";
                        if (dbOperate.Del_Ins_Upd_Result(sql) > 0) {
                            RefreshUserInfo();
                            MessageBox.Show("添加成功!", "提示", MessageBoxButtons.OK);
                            ClearUserInfo();
                        } else
                            MessageBox.Show("添加失败,请查找原因", "提示", MessageBoxButtons.OK);
                    }
                } catch (Exception) {
                    MessageBox.Show("添加失败,请查找原因", "提示", MessageBoxButtons.OK);
                }
            }
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        private void btnModifyUserInfo_Click(object sender, EventArgs e) {
            if (txtUserID.Text == "" || txtUserName.Text == "" || txtUserPsd.Text == "") {
                MessageBox.Show("员工信息不完整,无法添加!带*为必填选项", "提示", MessageBoxButtons.OK);
            } else {
                string sql = string.Empty;
                string strIsAdmin = string.Empty;
                try {
                    strIsAdmin = chkIsAdmin.Checked == true ? "1" : "0";
                    sql = "update userInfo set UserID='" + txtUserID.Text + "',UserName='" + txtUserName.Text + "',UserPsd='" + txtUserPsd.Text + "',IsAdmin='" + strIsAdmin + "'";
                    sql += " where UserID='" + txtUserID.Text + "'";
                    if (dbOperate.Del_Ins_Upd_Result(sql) > 0) {
                        RefreshUserInfo();
                        MessageBox.Show("修改成功", "提示", MessageBoxButtons.OK);
                        ClearUserInfo();
                    } else
                        MessageBox.Show("修改失败,请查找原因", "提示", MessageBoxButtons.OK);
                } catch (Exception) {
                    MessageBox.Show("修改失败,请查找原因", "提示", MessageBoxButtons.OK);
                }
            }
        }
        /// <summary>
        /// 删除用户信息
        /// </summary>
        private void btnDelUserInfo_Click(object sender, EventArgs e) {
            if (txtUserID.Text == "" || txtUserName.Text == "") {
                MessageBox.Show("请选择要删除的记录", "提示", MessageBoxButtons.OK);
            } else {
                if (MessageBox.Show("确定要删除该员工信息吗?\n" + "员工账号:" + txtUserID.Text + "\n" + "员工姓名:" + txtUserName.Text, "删除前确认", MessageBoxButtons.YesNo) == DialogResult.Yes) {
                    try {
                        string sql = "select * from userInfo where UserID='" + txtUserID.Text + "' and UserName='" + txtUserName.Text + "'";
                        if (dbOperate.intSelectResultCount(sql) > 0) {
                            sql = "delete from UserInfo where UserID='" + txtUserID.Text + "' and UserName='" + txtUserName.Text + "'";
                            dbOperate.Del_Ins_Upd_Result(sql);
                            RefreshUserInfo();
                            MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK);
                            ClearUserInfo();
                        } else
                            MessageBox.Show("删除失败,数据库中无此员工信息", "提示", MessageBoxButtons.OK);
                    } catch (Exception) {
                        MessageBox.Show("删除失败,请查找原因", "提示", MessageBoxButtons.OK);
                    }
                }
            }
        }
        private void txtUserID_KeyPress(object sender, KeyPressEventArgs e) {
            if (!(char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8) {
                e.Handled = true;
            }
        }
        /// <summary>
        /// 刷新用户信息
        /// </summary>
        private void RefreshUserInfo() {
            string sql = "select * from userInfo";
            DataTable dt = dbOperate.dtSelectResult(sql);
            dgvUserInfo.DataSource = dt;
        }
        /// <summary>
        /// 清除用户信息
        /// </summary>
        private void ClearUserInfo() {
            txtUserID.Text = "";
            txtUserName.Text = "";
            txtUserPsd.Text = "";
            chkIsAdmin.Checked = false;
        }

        private void dgvUserInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
            if (e.ColumnIndex == 3) {
                if (e.Value != null && e.Value.ToString().Length > 0) {
                    e.Value = new string('*', e.Value.ToString().Length);
                }
            }
            if (e.ColumnIndex == 4) {
                if (e.Value.Equals("1")) {
                    e.Value = "是";
                } else
                    e.Value = "否";
            }
        }

        private void dgvUserInfo_CellClick(object sender, DataGridViewCellEventArgs e) {
            try {
                txtUserID.Text = dgvUserInfo.Rows[e.RowIndex].Cells[1].Value.ToString();
                txtUserName.Text = dgvUserInfo.Rows[e.RowIndex].Cells[2].Value.ToString();
                txtUserPsd.Text = dgvUserInfo.Rows[e.RowIndex].Cells[3].Value.ToString();
                chkIsAdmin.Checked = dgvUserInfo.Rows[e.RowIndex].Cells[4].Value.ToString() == "1" ? true : false;
            } catch (Exception) {

            }
        }

        public DataTable dt;
        private void btnSelect_Click(object sender, EventArgs e) {
            if(cboSelectItems.SelectedIndex == 0) {
                if (txtSelectContent.Text == "") {
                    MessageBox.Show("请输入要查询的用户ID");
                    return;
                } else {
                    /*string sql = "select * from userInfo where UserID='" + txtSelectContent.Text + "'";
                    dt = new DataTable();
                    dt = dbOperate.GetDataTableFromDB(sql);
                    //查询信息界面
                    SelectInfo selectInfo = new SelectInfo(dt);
                    //selectInfo.ShowDialog();
                    selectInfo.Show(this);*/
                    string sql = "select * from userInfo where UserID='" + txtSelectContent.Text + "'";
                    if (dbOperate.intSelectResultCount(sql) > 0) {
                        dt = new DataTable();
                        dt = dbOperate.GetDataTableFromDB(sql);
                        //查询信息界面
                        SelectInfo selectInfo = new SelectInfo(dt);
                        //selectInfo.ShowDialog();
                        selectInfo.Show(this);                     
                    } else {
                        MessageBox.Show("查无此人", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            } else {
                if (txtSelectContent.Text == "") {
                    MessageBox.Show("请输入要查询的用户姓名");
                    return;
                } else {
                    string sql = "select * from userInfo where UserName= '" + txtSelectContent.Text + "'";
                    if (dbOperate.intSelectResultCount(sql) > 0) {
                        dt = new DataTable();
                        dt = dbOperate.GetDataTableFromDB(sql);
                        SelectInfo selectInfo = new SelectInfo(dt);
                        //selectInfo.ShowDialog();
                        selectInfo.Show(this);
                    } else {
                        MessageBox.Show("查无此人", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            
        }

        /// <summary>
        /// 将员工信息写入FileConfig.ini配置文件
        /// </summary>
        private void btnWrite_Click(object sender, EventArgs e) {
            if ((txtUserID.Text.Trim() != "") && (txtUserName.Text.Trim() != "") && txtUserPsd.Text.Trim() != "") {
                int ret;
                ret = fileOperation.WriteFile(strFilePath, "UserID", txtUserID.Text);
                ret = fileOperation.WriteFile(strFilePath, "UserName", txtUserName.Text);
                ret = fileOperation.WriteFile(strFilePath, "UserPsd", txtUserPsd.Text);
                if (ret == -1) {
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK);
                } else {
                    MessageBox.Show("保存失败", "提示", MessageBoxButtons.OK);
                }
            } else {
                MessageBox.Show("工号或姓名不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 将员工信息从FileConfig.ini文件中读出
        /// </summary>
        private void btnRead_Click(object sender, EventArgs e) {
            strUserId = fileOperation.ReadFile(strFilePath, "UserID");
            strUserName = fileOperation.ReadFile(strFilePath, "UserName");
            strPassword = fileOperation.ReadFile(strFilePath, "UserPsd");

            txtUserID.Text = strUserId;
            txtUserName.Text = strUserName;
            txtUserPsd.Text = strPassword;
        }
    }
}

点击查看代码。SelectInfo类--查询结果的界面。主要用来显示查询到的用户信息。这里根据个人需要,如果不需要重新新建一个几面来显示查询到的信息,则可以把界面里面的DataGridView放到FrmUserManager类中。
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 UserInfoManage.from {
    public partial class SelectInfo : Form {
        private DataTable dt;
        public SelectInfo(DataTable dt) {
            InitializeComponent();
            this.dt = dt;
        }

        private void SelectInfo_Load(object sender, EventArgs e) {
            dgvSelectInfo.DataSource = dt;
        }

        private void dgvSelectInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
            if (e.ColumnIndex == 3 && e.RowIndex != 0) {
                if (e.Value != null && e.Value.ToString().Length > 0) {
                    e.Value = new string('*', e.Value.ToString().Length);
                }
            }
            if (e.ColumnIndex == 4) {
                if (e.Value.Equals("1")) {
                    e.Value = "是";
                } else {
                    e.Value = "否";
                }
            }
        }
    }
}



这篇关于C#+Access 员工信息管理--简单的增删改查操作和.ini配置文件的读写操作。的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程