vs2010连接mysql数据库进行增删改查操作

来源:互联网 发布:激光去黑眼圈 知乎 编辑:程序博客网 时间:2024/05/29 15:47

.h文件


// STUDENTDlg.h : 头文件
//

#pragma once
#include "afxwin.h"
#include "afxcmn.h"

// CSTUDENTDlg 对话框
class CSTUDENTDlg : public CDialogEx
{
// 构造
public:
    CSTUDENTDlg(CWnd* pParent = NULL);    // 标准构造函数

// 对话框数据
    enum { IDD = IDD_STUDENT_DIALOG };

    MYSQL mysql;
    int oldStuId;
    CString sqlsel;
    bool ConDB();
    void Info(CString pSqlStr);
    void InitEdt();

    CString Utf8ToStr( const char* _pchSrc );
    int StrToUtf8( CString _Src, OUT char** ppchDes );

    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
    HICON m_hIcon;

    // 生成的消息映射函数
    virtual BOOL OnInitDialog();
    afx_msg void OnPaint();
    afx_msg HCURSOR OnQueryDragIcon();
    DECLARE_MESSAGE_MAP()
public:
    afx_msg void OnBnClickedBtnAdd();
    afx_msg void OnBnClickedBtnModify();
    afx_msg void OnBnClickedBtnDel();
    afx_msg void OnBnClickedBtnSelect();
    CEdit mEdtStuId;
    CEdit mEdtName;
    CEdit mEdtSex;
    CEdit mEdtAge;
    CEdit mEdtSelect;
    
    CListCtrl mListStu;

    afx_msg void OnNMClickListStu(NMHDR *pNMHDR, LRESULT *pResult);
};

.cpp文件


// STUDENTDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "STUDENT.h"
#include "STUDENTDlg.h"
#include "afxdialogex.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CSTUDENTDlg 对话框




CSTUDENTDlg::CSTUDENTDlg(CWnd* pParent /*=NULL*/)
    : CDialogEx(CSTUDENTDlg::IDD, pParent)
{
    m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
    sqlsel="select * from mytable;";
}

void CSTUDENTDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_EDIT_STUID, mEdtStuId);
    DDX_Control(pDX, IDC_EDIT_NAME, mEdtName);
    DDX_Control(pDX, IDC_EDIT_SEX, mEdtSex);
    DDX_Control(pDX, IDC_EDIT_AGE, mEdtAge);
    DDX_Control(pDX, IDC_EDIT_SELECT, mEdtSelect);

    DDX_Control(pDX, IDC_LIST_STU, mListStu);
}

BEGIN_MESSAGE_MAP(CSTUDENTDlg, CDialogEx)
    ON_WM_PAINT()
    ON_WM_QUERYDRAGICON()
    ON_BN_CLICKED(IDC_BTN_ADD, &CSTUDENTDlg::OnBnClickedBtnAdd)
    ON_BN_CLICKED(IDC_BTN_MODIFY, &CSTUDENTDlg::OnBnClickedBtnModify)
    ON_BN_CLICKED(IDC_BTN_DEL, &CSTUDENTDlg::OnBnClickedBtnDel)
    ON_BN_CLICKED(IDC_BTN_SELECT, &CSTUDENTDlg::OnBnClickedBtnSelect)
//
ON_NOTIFY(NM_CLICK, IDC_LIST_STU, &CSTUDENTDlg::OnNMClickListStu)
END_MESSAGE_MAP()


// CSTUDENTDlg 消息处理程序

BOOL CSTUDENTDlg::OnInitDialog()
{
    CDialogEx::OnInitDialog();

    // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
    //  执行此操作
    SetIcon(m_hIcon, TRUE);            // 设置大图标
    SetIcon(m_hIcon, FALSE);        // 设置小图标

    // TODO: 在此添加额外的初始化代码

    mListStu.SetExtendedStyle(LVS_EX_FLATSB|LVS_EX_FULLROWSELECT|
    LVS_EX_HEADERDRAGDROP|LVS_EX_ONECLICKACTIVATE|LVS_EX_GRIDLINES);
    
    mListStu.InsertColumn(0,L"学号",LVCFMT_LEFT,125,-1);
    mListStu.InsertColumn(1,L"姓名",LVCFMT_LEFT,125,-1);
    mListStu.InsertColumn(2,L"性别",LVCFMT_LEFT,125,-1);
    mListStu.InsertColumn(3,L"年龄",LVCFMT_LEFT,125,-1);


    if(ConDB()) Info(sqlsel);//读取数据库数据

    return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

// 如果向对话框添加最小化按钮,则需要下面的代码
//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
//  这将由框架自动完成。

void CSTUDENTDlg::OnPaint()
{
    if (IsIconic())
    {
        CPaintDC dc(this); // 用于绘制的设备上下文

        SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

        // 使图标在工作区矩形中居中
        int cxIcon = GetSystemMetrics(SM_CXICON);
        int cyIcon = GetSystemMetrics(SM_CYICON);
        CRect rect;
        GetClientRect(&rect);
        int x = (rect.Width() - cxIcon + 1) / 2;
        int y = (rect.Height() - cyIcon + 1) / 2;

        // 绘制图标
        dc.DrawIcon(x, y, m_hIcon);
    }
    else
    {
        CDialogEx::OnPaint();
    }
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CSTUDENTDlg::OnQueryDragIcon()
{
    return static_cast<HCURSOR>(m_hIcon);
}

bool CSTUDENTDlg::ConDB()
{
    
    mysql_init(&mysql);
    mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, "utf8"); //设置字符集
    if(mysql_real_connect(&mysql,"localhost","root","root","mydb",3306,NULL,0)==NULL)
    {
        MessageBox(L"数据库连接失败!",L"连接数据库");
        return false;
    }else
    {
        
    }
    //gun
//    mysql_query(&mysql,"set names utf8");
}

void CSTUDENTDlg::OnBnClickedBtnAdd()
{
    // TODO: 在此添加控件通知处理程序代码
    
    CString name;
    CString sex;    

    int stuId=GetDlgItemInt(IDC_EDIT_STUID);
    int age=GetDlgItemInt(IDC_EDIT_AGE);
    mEdtName.GetWindowText(name);
    mEdtSex.GetWindowText(sex);
//    GetDlgItemText(IDC_EDIT_NAME,name);
//    GetDlgItemText(IDC_EDIT_SEX,sex);
    
    if(stuId==0||age==0||stuId<0||age<0)
    {
        MessageBox(L"请正确填写学号或年龄!",L"温馨提示");
        return;
    }
    if(name==""||sex=="")
    {
        MessageBox(L"请正确填写姓名或性别!",L"温馨提示");
        return;
    }
    
    CString sqlStr;        
    sqlStr.Format(L"insert into mytable values(%d,'%s','%s',%d);",stuId,name,sex,age);
    char* p=NULL;
    StrToUtf8(sqlStr,&p);
    
    //OutputDebugString(sqlStr);
    //USES_CONVERSION;
    //char* p=T2A(sqlStr);    
    int a=mysql_real_query(&mysql,p,strlen(p));
    delete []p;
    if(a==0)
    {

    }else
    {
        MessageBox(L"添加失败",L"温馨提示");
        return;
    }
    
    InitEdt();
    Info(sqlsel);
}


void CSTUDENTDlg::OnBnClickedBtnModify()
{
    // TODO: 在此添加控件通知处理程序代码
    CString name,sex;
    mEdtName.GetWindowText(name);
    mEdtSex.GetWindowText(sex);
    
    int stuId=GetDlgItemInt(IDC_EDIT_STUID);
    int age=GetDlgItemInt(IDC_EDIT_AGE);

    CString str;
    str.Format(L"update mytable set stuID=%d, name='%s' ,sex='%s', age=%d where stuID=%d;",stuId,name,sex,age,oldStuId);
    char* p=NULL;
    this->StrToUtf8(str,&p);
    int a=mysql_real_query(&mysql,p,strlen(p));
    if(a==0)
    {

    }else
    {
        MessageBox(L"修改失败",L"温馨提示");
        return;
    }
    InitEdt();
    Info(sqlsel);
}


void CSTUDENTDlg::OnBnClickedBtnDel()
{
    // TODO: 在此添加控件通知处理程序代码

    int stuId=GetDlgItemInt(IDC_EDIT_STUID);
    
    if(stuId==0)
    {
        MessageBox(L"请选择一行删除!",L"温馨提示");
        return;
    }
    CString str;
    str.Format(L"delete from mytable where stuID=%d;",stuId);
    char* p=NULL;
    this->StrToUtf8(str,&p);
    int a=mysql_real_query(&mysql,p,strlen(p));
    delete []p;
    if(a==0)
    {

    }else
    {
        MessageBox(L"删除失败!",L"温馨提示");
        return;
    }
    

    InitEdt();
    Info(sqlsel);

}


void CSTUDENTDlg::OnBnClickedBtnSelect()
{
    // TODO: 在此添加控件通知处理程序代码
    CString name;
    mEdtSelect.GetWindowText(name);
    CString str;
    if(name=="")
    {
        str=sqlsel;
    }else
    {
        str.Format(L"select * from mytable where name like '%s%s';",name,"%");
    }
    Info(str);
}

void CSTUDENTDlg::Info(CString pSqlStr)
{
    mListStu.DeleteAllItems();
    char* p=NULL;
    this->StrToUtf8(pSqlStr,&p);
    int a=mysql_real_query(&mysql,p,strlen(p));
    delete []p;
    if(a==0)
    {

    }else
    {
        MessageBox(L"查询数据库错误!",L"温馨提示");
        return;
    }

    CString str;
    MYSQL_RES* result;
    MYSQL_ROW row;
    if((result=mysql_use_result(&mysql))==0)
    {
        MessageBox(L"读取数据失败!",L"温馨提示");
        return;
    }else
    {
        
    }
    int i=0;
    while(row=mysql_fetch_row(result))
    {
        
        mListStu.InsertItem(i,L"");
        str.Format(L"%s",Utf8ToStr(row[0]));
        OutputDebugString(str);
        mListStu.SetItemText(i,0,str);
        str.Format(L"%s",Utf8ToStr(row[1]));
        mListStu.SetItemText(i,1,str);
        OutputDebugString(str);
        str.Format(L"%s",Utf8ToStr(row[2]));
        mListStu.SetItemText(i,2,str);
        str.Format(L"%s",Utf8ToStr(row[3]));
        mListStu.SetItemText(i,3,str);
        i++;
    }
    mysql_free_result(result);
//    mysql_close(&mysql);
}

CString CSTUDENTDlg::Utf8ToStr( const char* _pchSrc )
{
    if(_pchSrc == NULL)
    {
        return _T("");
    }
    DWORD dwLength = MultiByteToWideChar(CP_UTF8, 0, _pchSrc, -1, NULL, 0);
    TCHAR* pwText = new TCHAR[dwLength];
    MultiByteToWideChar(CP_UTF8, 0, _pchSrc, -1, pwText, dwLength);
    CString tstrText = pwText;
    delete []pwText;
    return tstrText;
}

int CSTUDENTDlg::StrToUtf8( CString _Src, OUT char** ppchDes )
{
    DWORD dwLength = WideCharToMultiByte(CP_UTF8, NULL, _Src, -1, NULL, 0, NULL, FALSE);
    *ppchDes = new char[dwLength];
    WideCharToMultiByte(CP_UTF8, 0, _Src, -1, *ppchDes, dwLength, NULL, FALSE);
    return dwLength;
}



void CSTUDENTDlg::OnNMClickListStu(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
    // TODO: 在此添加控件通知处理程序代码
    int pos=mListStu.GetSelectionMark();

    CString stuId=mListStu.GetItemText(pos,0);
    CString name=mListStu.GetItemText(pos,1);
    CString sex=mListStu.GetItemText(pos,2);
    CString age=mListStu.GetItemText(pos,3);

    oldStuId=_ttoi(stuId);

    mEdtStuId.SetWindowText(stuId);
    mEdtName.SetWindowText(name);
    mEdtSex.SetWindowText(sex);
    mEdtAge.SetWindowText(age);
    
    *pResult = 0;
}
void CSTUDENTDlg::InitEdt()
{
    mEdtStuId.SetWindowText(L"");
    mEdtName.SetWindowText(L"");
    mEdtSex.SetWindowText(L"");
    mEdtAge.SetWindowText(L"");
}


原创粉丝点击