嵌入C结构 - Python中的函数

时间:2014-09-14 17:34:19

标签: python c

我正在编写一个应该嵌入Python代码的MySql C程序。出于演示目的,程序将在数据库上执行MySql INSERT和SELECT命令。如何使这个结构和函数在python代码中工作并将MySql结果传递给python或cdef变量。

有人可以提前帮助吗?

这是我的工作代码:

HEADER FILE:“chi2.h”

struct _MYSQL
{
char *server;
char *user;
char *password;
char *database;
char *table;
char *ptr_statement;
char *user_input;
MYSQL *connection;
MYSQL_RES *result;
};
MYSQL_RES *_GET_MYSQL(struct _MYSQL *DATA);

C代码文件:“chi2.c”

#include "/usr/include/python2.7/Python.h"
#include "mysql.h"
#include "stdio.h"
#include "stdlib.h"
#include "chi2.h"

MYSQL_RES *_GET_MYSQL(struct _MYSQL *DATA)
{
DATA->result = NULL;
DATA->ptr_statement = NULL;
DATA->connection = mysql_init(NULL);

/* Connect to database */
if (!mysql_real_connect(DATA->connection, DATA->server, DATA->user, DATA->password, DATA->database, 0, NULL, 0))
{
mysql_close(DATA->connection);
fprintf(stderr, "%s\n", mysql_error(DATA->connection));
exit(1);
}

/* Get MySql query */
DATA->ptr_statement = malloc(sizeof(int) * 16);   // int is 4 bytes * 16 (64 bytes * 8 = 512 bits)
snprintf(DATA->ptr_statement, *(DATA)->ptr_statement, "INSERT INTO hash (hash_name) VALUES ('%s')", DATA->user_input);
if(mysql_query(DATA->connection, DATA->ptr_statement))
{
free(DATA->ptr_statement);
DATA->user_input = NULL;
mysql_close(DATA->connection);
fprintf(stderr, "%s\n", mysql_error(DATA->connection));
exit(1);
}
mysql_commit(DATA->connection);
free(DATA->ptr_statement);
DATA->user_input = NULL;

DATA->ptr_statement = malloc(sizeof(signed short int));   // short int is 2 bytes (16 bits)
sprintf(DATA->ptr_statement, "SELECT * FROM %s", DATA->table);
if (mysql_query(DATA->connection, DATA->ptr_statement))
{
free(DATA->ptr_statement);
mysql_close(DATA->connection);
fprintf(stderr, "%s\n", mysql_error(DATA->connection));
exit(1);
}

mysql_commit(DATA->connection);
free(DATA->ptr_statement);
DATA->result = mysql_use_result(DATA->connection);
return DATA->result;
mysql_close(DATA->connection);
mysql_free_result(DATA->result);
}

int main(int argc, char *argv[])
{
struct _MYSQL *DAT;
MYSQL_ROW ROW;
MYSQL_RES *RESULT = NULL;

DAT->server = "localhost";
DAT->user = "test1";
DAT->password = "test1";
DAT->database = "test";

DAT->table = "hash";
DAT->user_input = "HELLO :D";
RESULT = _GET_MYSQL(&(*DAT));
while ((ROW = mysql_fetch_row(RESULT)) != NULL)
printf("%s - %s \n", ROW[0], ROW[1]);
}

mysql_free_result(RESULT);
RESULT = NULL;
ROW = NULL;
DAT->table = NULL;
DAT->user_input = NULL;

//fflush(stdin);
//system("clear");
return EXIT_SUCCESS;
}

0 个答案:

没有答案