linux下C语言连接mysql
#include
#include
#include
MYSQL mysql;
void doQuery() {
MYSQL_ROW m_row;
MYSQL_RES *m_res;
MYSQL_FIELD *m_field;
char sql[1024];
sprintf(sql,"select * from account");
if(mysql_query(&mysql,sql) != 0) {
printf("mysql_query err: %s\n",mysql_error(&mysql));
}
m_res = mysql_store_result(&mysql);
if(m_res==NULL) {
printf("get result err: %s\n",mysql_error(&mysql));
}
while( (m_field = mysql_fetch_field(m_res)) ) {
printf("field name %s\n", m_field->name);
}
int num_fields = mysql_num_fields( m_res );
for( int i = 0; i m_field = mysql_fetch_field_direct( m_res, i);
printf("Field %d is %s\n", i, m_field->name);
}
while( ( m_row = mysql_fetch_row( m_res ) ) != NULL ) {
num_fields = mysql_num_fields( m_res );
for ( int i=0; i printf("%s\n", m_row[i] != NULL ? m_row[i] : "NULL");
}
}
mysql_free_result(m_res);
}
int main() {
char host[32] = "localhost";
char user[32] = "root";
char passwd[32] = "";
char db[32] = "test";
if( mysql_init(&mysql) == NULL ) {
printf( "init mysql err!\n" );
return -1;
}
if (mysql_real_connect(&mysql,host,user,passwd,db,0,NULL,0) == NULL) {
printf("Connect to mysql Error:%s!\n",mysql_error(&mysql));
return -1;
}
else {
puts("Connect to mysql success!");
}
doQuery();
mysql_close(&mysql);
return 0;
}
编译需要链接mysqlclient库和zlib库(所以需要保证系统中安装了mysqlclient和c连接mysql的库
例如本例子中:
g++ test.cpp -o test.exe -L/usr/lib/mysql -lmysqlclient -lz
安装的位置不同-L/usr/lib/mysql要作相应修改。比如在64位下,就是-L/usr/lib64/mysql
连接数据库
mysql_real_connect(数据库句柄,主机名,用户名,密码,数据库名,端口,命名管道,客户端标记)
代码:
mysql_init(&mysql);
if(!mysql_real_connect(&mysql,"localhost","root","1","mydb",3306,NULL,0))
puts("数据库连接错误!");
如果连接成功,就可以进行数据库的读写了:
1.mysql_query() //提交查询语句
2.mysql_use_result() //获取上一次查询的结果集
3.mysql_fetch_row() //从结果集中获取单项内容
4.mysql_free_result() //释放结果集
5.mysql_fetch_lengths(result) //取得一行中每个字段的内容的长度。
其他相关函数例如:
mysql_fetch_array()、mysql_fetch_assoc()、mysql_fetch_object() 或 mysql_fetch_row()......
另外
mysql_character_set_name()//返回字符集名字
mysql_options(MYSQL *mysql, enum mysql_option option, const char *arg) //设置额外的连接参数
例如:ret = mysql_options(conn, MYSQL_SET_CHARSET_NAME, "gb2312");