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配置文件的读写操作。的更多相关文章

  1. MVC3.0+knockout.js+Ajax 实现简单的增删改查

    MVC3.0+knockout.js+Ajax 实现简单的增删改查 自从到北京入职以来就再也没有接触MVC,很多都已经淡忘了,最近一直在看knockout.js 和webAPI,本来打算采用MVC+k ...

  2. salesforce 零基础学习(五十一)使用 Salesforce.com SOAP API 实现用户登录以及简单的增删改查(JAVA访问salesforce)

    此篇请参看:https://resources.docs.salesforce.com/202/latest/en-us/sfdc/pdf/salesforce_developer_environme ...

  3. MyBatis学习--简单的增删改查

    jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...

  4. 通过JDBC进行简单的增删改查

    通过JDBC进行简单的增删改查(以MySQL为例) 目录 前言:什么是JDBC 一.准备工作(一):MySQL安装配置和基础学习 二.准备工作(二):下载数据库对应的jar包并导入 三.JDBC基本操 ...

  5. MyBatis简单的增删改查以及简单的分页查询实现

    MyBatis简单的增删改查以及简单的分页查询实现 <? xml version="1.0" encoding="UTF-8"? > <!DO ...

  6. 初试KONCKOUT+WEBAPI简单实现增删改查

    初试KONCKOUT+WEBAPI简单实现增删改查 前言 konckout.js本人也是刚刚接触,也是初学,本文的目的是使用ko和asp.net mvc4 webapi来实现一个简单增删改查操作.Kn ...

  7. SpringMVC之简单的增删改查示例(SSM整合)

    本篇文章主要介绍了SpringMVC之简单的增删改查示例(SSM整合),这个例子是基于SpringMVC+Spring+Mybatis实现的.有兴趣的可以了解一下. 虽然已经在做关于SpringMVC ...

  8. python3.6 使用 pymysql 连接 Mysql 数据库及 简单的增删改查操作

    1.通过 pip 安装 pymysql 进入 cmd  输入  pip install pymysql   回车等待安装完成: 安装完成后出现如图相关信息,表示安装成功. 2.测试连接 import ...

  9. 通过flask实现web页面简单的增删改查bootstrap美化版

    通过flask实现web页面简单的增删改查bootstrap美化版 项目目录结构 [root@node1 python]# tree -L 2 . ├── animate.css ├── fileut ...

随机推荐

  1. 关于IIS站点最大并发量分析

    关于IIS站点最大并发量分析,会有如下这个疑问:IIS站点最大并发量是多少? 一般为:   IIS站点最大并发量=队列长度+进程数量[即最大工作进程数] 通过这个公式,可以基本评估出一个IIS站点的最 ...

  2. kvm管理查看信息,添加,删除,暂停恢复,克隆等

    KVM virsh管理指令 virsh 查看帮助信息 查看命令帮助 [root@KVM ~]# virsh Welcome to virsh, the virtualization interacti ...

  3. 不会DRF?源码都分析透了确定不来看?

    目录 不会DRF?源码都分析透了确定不来看? 快速使用DRF写出接口 序列化和反序列化 drf快速使用 views.py serializer.py urls.py 在settings的app中注册 ...

  4. @Transactional注解的失效场景

    一口气说出 6种,@Transactional注解的失效场景 计算机java编程 发布时间: 20-03-1912:35优质科技领域创作者 引言 昨天公众号粉丝咨询了一个问题,说自己之前面试被问@Tr ...

  5. uWSGI+django+nginx的工作原理流程与部署

    二.必要的前提 2.1 准备知识 django 一个基于python的开源web框架,请确保自己熟悉它的框架目录结构. uWSGI 一个基于自有的uwsgi协议.wsgi协议和http服务协议的web ...

  6. Java 中如何将字符串转换为整数?

    String s="123"; int i; 第一种方法:i=Integer.parseInt(s); 第二种方法:i=Integer.valueOf(s).intValue();

  7. notify()和 notifyAll()有什么区别?

    当一个线程进入 wait 之后,就必须等其他线程 notify/notifyall,使用 notifyall,可 以唤醒所有处于 wait 状态的线程,使其重新进入锁的争夺队列中,而 notify 只 ...

  8. MariaDB CAST语法

    Syntax CAST(expr AS type) Description CAST()函数采用一种类型的值,并产生另一种类型的值,类似于CONVERT函数. CAST()和CONVERT()之间的主 ...

  9. 说说对 SQL 语句优化有哪些方法?

    1.Where 子句中:where 表之间的连接必须写在其他 Where 条件之前,那些可 以过滤掉最大数量记录的条件必须写在 Where 子句的末尾.HAVING 最后. 2.用 EXISTS 替代 ...

  10. springboot使用redis实现发布与订阅

    配置redis连接地址 # Redis服务器地址 spring.redis.host=youxiu326.xin # Redis服务器连接端口 spring.redis.port=6379 # Red ...