C#结合数据库实现验证识别ID卡内容的方法
本文所述实例为C#结合数据库,来验证所识别的ID卡内容,通过本实例代码,用户可以轻松实现对ID卡会员信息的验证。该实例代码可实现读取数据库,进而逐步实现数据库连接,数据库读取,ID卡读取,ID卡信息与数据库内容比对,最终返回结果并告之是否验证成功。
具体功能代码如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Data.OleDb; usingSystem.Runtime.InteropServices; usingSystem.Diagnostics; usingSystem.Collections; namespaceIDCard { publicpartialclassForm1:Form { publicForm1() { InitializeComponent(); } publicdelegateintHookProc(intnCode,intwParam,IntPtrlParam); staticinthHook=0; publicconstintWH_KEYBOARD_LL=13; //LowLevel键盘截获,如果是WH_KEYBOARD=2,并不能对系统键盘截取,AcrobatReader会在你截取之前获得键盘。 HookProcKeyBoardHookProcedure; [DllImport("kernel32")] publicstaticexternintBeep(intdwFreq,intdwDuration);//让计算机蜂鸣 stringDataPath="";//数据库路径 OleDbConnectioncon;//OleDbConnection对象,连接数据库 OleDbCommandcmd;//OleDbCommand对象,执行SQL语句 //键盘Hook结构函数 [StructLayout(LayoutKind.Sequential)] publicclassKeyBoardHookStruct { publicintvkCode; publicintscanCode; publicintflags; publicinttime; publicintdwExtraInfo; } [DllImport("user32.dll")] publicstaticexternintSetWindowsHookEx(intidHook,HookProclpfn,IntPtrhInstance,intthreadId); [DllImport("user32.dll",CharSet=CharSet.Auto,CallingConvention=CallingConvention.StdCall)] //抽掉钩子 publicstaticexternboolUnhookWindowsHookEx(intidHook); [DllImport("user32.dll")] //调用下一个钩子 publicstaticexternintCallNextHookEx(intidHook,intnCode,intwParam,IntPtrlParam); [DllImport("kernel32.dll")] publicstaticexternIntPtrGetModuleHandle(stringname); publicstringgetNum(stringcode) { stringflag=""; switch(code) { case"048": flag="0";break; case"049": flag="1";break; case"050": flag="2";break; case"051": flag="3";break; case"052": flag="4";break; case"053": flag="5";break; case"054": flag="6";break; case"055": flag="7";break; case"056": flag="8";break; case"057": flag="9";break; } returnflag; } publicvoidHook_Start() { //安装键盘钩子 if(hHook==0) { KeyBoardHookProcedure=newHookProc(KeyBoardHookProc); hHook=SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardHookProcedure, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName),0); //如果设置钩子失败. if(hHook==0) { Hook_Clear(); } } } //取消钩子事件 publicvoidHook_Clear() { boolretKeyboard=true; if(hHook!=0) { retKeyboard=UnhookWindowsHookEx(hHook); hHook=0; } //如果去掉钩子失败. if(!retKeyboard)thrownewException("UnhookWindowsHookExfailed."); } //这里可以添加自己想要的信息处理 stringNumCode=""; publicintKeyBoardHookProc(intnCode,intwParam,IntPtrlParam) { if(nCode>=0) { if(wParam==0x0104||wParam==0x0100) { KeyBoardHookStructkbh=(KeyBoardHookStruct)Marshal.PtrToStructure(lParam,typeof(KeyBoardHookStruct)); intflag=kbh.vkCode; switch(flag) { case96: NumCode+="0";break; case97: NumCode+="1";break; case98: NumCode+="2";break; case99: NumCode+="3";break; case100: NumCode+="4";break; case101: NumCode+="5";break; case102: NumCode+="6";break; case103: NumCode+="7";break; case104: NumCode+="8";break; case105: NumCode+="9";break; } if(flag==13) { if(NumCode.Length!=0) { stringc=""; stringid=""; for(inti=0;i<=NumCode.Length-3;i+=3) { stringb=NumCode.Substring(i,3); c+=getNum(b); } id=c; if(id.Length==8)//如果卡号为8位 { //实例化OleDbConnection对象 con=newOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Datasource="+DataPath); con.Open();//打开数据库连接 //实例化OleDbCommand对象,根据ID卡号检索数据表 cmd=newOleDbCommand("select*fromtb_UserInfowhereCardID='"+id+"'",con); OleDbDataReadersdr=cmd.ExecuteReader();//实例化OleDbDataReader对象 sdr.Read();//读取记录 txtShowCardID.Text=id;//获取ID卡号 txtShowName.Text=sdr["UName"].ToString();//获取员工姓名 cbbShowSex.Text=sdr["USex"].ToString();//获取员工性别 cbbShowDep.Text=sdr["UDep"].ToString();//获取员工部门 con.Close();//关闭数据库连接 Beep(3000,100);//计算机蜂鸣 } NumCode=""; } } } } returnCallNextHookEx(hHook,nCode,wParam,lParam); } privatevoidForm1_Load(objectsender,EventArgse) { cbbdep.SelectedIndex=0;//设置部门下拉框的第一项被选中 cbbsex.SelectedIndex=0;//设置性别下拉框的第一项被选中 //获取数据库路径 DataPath=Application.StartupPath.ToString(); DataPath=DataPath.Substring(0,DataPath.LastIndexOf("\\")); DataPath=DataPath.Substring(0,DataPath.LastIndexOf("\\")); DataPath+=@"\db.mdb"; } privatevoidradioButton1_CheckedChanged(objectsender,EventArgse) { if(radioButton1.Checked) { groupBox1.Enabled=true; Hook_Clear(); } } privatevoidradioButton2_CheckedChanged(objectsender,EventArgse) { if(radioButton2.Checked) { groupBox1.Enabled=false; Hook_Start(); } } privatevoidbutton2_Click(objectsender,EventArgse) { txtIdcard.Text=""; txtName.Text=""; } privatevoidbutton1_Click(objectsender,EventArgse) { if(txtIdcard.Text==""||txtName.Text=="")//如果没有输入ID卡号和员工姓名 { //弹出警告信息 if(MessageBox.Show("请将数据填写完整!","警告",MessageBoxButtons.OK,MessageBoxIcon.Error)==DialogResult.OK) { if(txtIdcard.Text=="")//如果没有输入ID卡号 txtIdcard.Focus();//则光标处在输入ID卡号的文本框 if(txtName.Text=="")//如果没有输入员工姓名 txtName.Focus();//则光标处在输入员工姓名的文本框 if(txtIdcard.Text==""&&txtName.Text=="")//如果都没输入数据 txtIdcard.Focus();//则光标处在输入ID卡号的文本框 } } else//如果输入了数据 { if(txtIdcard.Text.Trim().Length!=8)//如果输入的ID卡号不是8位 { //弹出警告信息 if(MessageBox.Show("ID卡号必须为8位!","警告",MessageBoxButtons.OK,MessageBoxIcon.Error)==DialogResult.OK) { txtIdcard.Text="";//清空输入ID卡号的文本框 txtIdcard.Focus();//让光标处在输入ID卡号的文本框上 } } else//如果输入的ID卡号为8位 { //实例化OleDbConnection对象 con=newOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Datasource="+DataPath); con.Open();//打开连接 //实例化OleDbCommand对象 cmd=newOleDbCommand("selectcount(*)fromtb_UserInfowhereCardID='"+txtIdcard.Text.Trim()+"'",con); intflag=Convert.ToInt32(cmd.ExecuteScalar());//判断是否已经添加过此ID卡号 if(flag>0)//如果大于0则说明已经添加过 { //弹出警告信息 if(MessageBox.Show("ID卡号已经添加过了!","警告",MessageBoxButtons.OK,MessageBoxIcon.Error)==DialogResult.OK) { button2_Click(sender,e);//清空输入ID卡号和员工姓名的文本框 } } else//如果小于0说明没有添加过 { //实例化OleDbCommand对象 cmd=newOleDbCommand("insertintotb_UserInfo(CardID,UName,USex,UDep)values('"+txtIdcard.Text.Trim()+"','"+txtName.Text.Trim()+"','"+cbbsex.Text.Trim()+"','"+cbbdep.Text.Trim()+"')",con); intk=cmd.ExecuteNonQuery();//执行insert语句,将输入的信息添加到数据库中 if(k>0)//如果大于0则操作成功 { //弹出提示信息 if(MessageBox.Show("添加成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information)==DialogResult.OK) { button2_Click(sender,e);//清空输入ID卡号和员工姓名的文本框 } } } con.Close();//关闭数据库连接 } } } privatevoidtxtIdcard_KeyPress(objectsender,KeyPressEventArgse) { if(!(e.KeyChar<='9'&&e.KeyChar>='0')&&e.KeyChar!='\r'&&e.KeyChar!='\b') { e.Handled=true; } } } }
该实例注释完善,便于阅读,读者还可以根据自身需求改善代码,或者添加新的功能以满足自身应用的个性化需求。