MySQL for Linux on POWER 开发应用
2008-01-18 11:06:14 来源:WEB开发网本节给出了一个示例,介绍如何在 POWER 和 PPC 上的 Linux 中使用用于 MySQL 的官方 C API。
下面是一个简单的代码示例,展示了连接到 MySQL 数据库并从中获取数据所需要的标准函数调用:
清单 3. C 代码示例
#include <stdlib.h>
#include <stdio.h>
#include <mysql.h>
int
main(int argc, char **argv) {
MYSQL mysql;
MYSQL_RES *res;
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
char *query="SELECT * FROM JOB";
/*Initializing MySQL connection*/
if(mysql_init(&mysql)==NULL) {
printf("Failed to initate MySQL connection
");
exit(1);
}
/*Connecting to MySQL server*/
if (!mysql_real_connect(&mysql,"127.0.0.1","username","password",NULL,0
,NULL,0)) {
printf( "Failed connect to the server: %s
",
mysql_error(&mysql));
exit(1);
}
/*Selecting database*/
if(mysql_select_db(&mysql,"CONTRACTING")!=0)
printf( "Failed select CONTRACTING: %s
", mysql_error(&mysql));
/*Performing SQL query*/
if(mysql_query(&mysql,query)) {
printf("MySQL query error: %s
",mysql_error(&mysql));
mysql_close(&mysql);
exit(1);
}
res = mysql_store_result(&mysql);
if (res) {
num_fields = mysql_num_fields(res);
while ((row = mysql_fetch_row(res)))
{
for(i = 0; i < num_fields; i++) {
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("
");
}
mysql_free_result(res);
}
else {
if(mysql_field_count(&mysql) > 0)
{
printf( "Error getting records: %s
", mysql_error(&mysql));
}
else {
printf( "Failed to find any records and caused an error:
%s
", mysql_error(&mysql));
}
}
mysql_close(&mysql);
}
更多精彩
赞助商链接