xml地图|网站地图|网站标签 [设为首页] [加入收藏]

MFC连接Mysql数据库执行查询和插入

配置环境:

配置环境:

    include:libpq-fe.h文件

    include:mysql.h文件

    lib:libpq.lib文件

    lib:libmysql.lib文件

    dll:libeay32.dll,libiconv-2.dll,libintl-8.dll,libpq.dll,ssleay32.dll五个文件

    dll:;libmysql.dll文件

连接代码: 

连接代码:

PGresult *res;//存放结果
PGconn *m_conn;

MYSQL m_sqlCon;
MYSQL_RES *m_res;
MYSQL_ROW row;

//连接数据库

//初始化数据库
mysql_init(&m_sqlCon);
// 设置连接数据库字符串
CString conn_ip,conn_port,conn_dbname,conn_user,conn_password;

必威,m_conn = PQsetdbLogin(ip,port,"","",dbname,user,password);

if(!mysql_real_connect(&m_sqlCon,conn_ip,conn_user,conn_password,conn_dbname,int_port,NULL,0))
{
  AfxMessageBox(_T("访问数据库失败!"));
  return;
}

PQsetClientEncoding(m_conn,"GBK");
if (PQstatus(m_conn) != CONNECTION_OK)
{
//连接数据库失败,就输出失败原因
CString strErr;
strErr.Format(_T("连接数据库失败 [%s]"),CString(PQerrorMessage(m_conn)));
AfxMessageBox(strErr);
PQfinish(m_conn);
return;
}

mysql_query(&m_sqlCon,"SET NAMES 'GB2312'");//解决从数据库中读取数据后汉字乱码显示的问题  

//定义数据库查询语句得到查询结果
string strsql = "select * from tb_way_performance where sp_way_id>0" ;
res = PQexec(m_conn, strsql.c_str());

//定义sql语句

//根据字段值获得字段way_id所在列

const char *sql = "select * from table";

int col_way_id = PQfnumber(res,"way_id");

//执行查询

//获取列值col_way_id 和行值i得到单元格的值

m_res = mysql_store_result(&m_sqlCon);

CString str_way_id(PQgetvalue(result,i,col_way_id));

//如果为空则返回

 

if(NULL == m_res)
{ return; }

最后附带libpq连接postgre数据库的api文档

//重复读取行,把数据放入列表中,直到row为NULL

while (row = mysql_fetch_row(m_res)) 
{
  for (int rols = 0; rols < 2; rols++)
  {
    CString myreaddata(row[rols]);
    list.AddString(myreaddata);
  }
}

//执行插入

const char *sql = "insert into tb_rdchange(way_id,sp_way_id) values(4,4)";
if(mysql_real_query(&m_sqlCon, sql,(unsigned long)strlen(sql)))
{
  return;
}

 

本文由必威发布于操作系统,转载请注明出处:MFC连接Mysql数据库执行查询和插入