linux下C操作mysql数据库基本函数

#include
#include


#include "mysql.h"


static MYSQL *SQL = NULL;


int mysqlConnection(const char* host, const char* user, const char* password, \
const char* database)
{//mysql_real_connect(SQL, "127.0.0.1", "root", "", "tank", 0, NULL, 0)
    mysql_init(SQL); 
 
    if (!mysql_real_connect(SQL, host, user, password, database, 0, NULL, 0)){
        fprintf(stderr, "MySql Connection failed!\n");
        if (mysql_errno(SQL)) {
            fprintf(stderr, "Connection error %d: %s\n", mysql_errno(SQL), mysql_error(SQL));
        }
        return -1;
    }
return 0;
}
 
int mysqlInsert(char *sql) 
{//sql = "INSERT INTO student(student_no,student_name) VALUES('123465', 'Ann')"
    int res = mysql_query(SQL, sql);
    if (!res) {
        printf("Inserted %lu rows\n", (unsigned long)mysql_affected_rows(SQL));
return 0;
    } else {
        fprintf(stderr, "Insert error %d: %s\n", mysql_errno(SQL), mysql_error(SQL));
return -1;
    }
}
 
int mysqlUpdate(char *sql) 
{//"UPDATE student SET student_name='Anna' WHERE student_no='123465'"
    int res = mysql_query(SQL, sql);
    if (!res) {
        printf("Update %lu rows\n", (unsigned long)mysql_affected_rows(SQL));
return 0;
    } else {
        fprintf(stderr, "Update error %d: %s\n", mysql_errno(SQL), mysql_error(SQL));
return -1;
    }
}
 
int mysqlDelete(char *sql) 
{//"DELETE from student WHERE student_no='123465'"
    int res = mysql_query(SQL, sql);
    if (!res) {
        printf("Delete %lu rows\n", (unsigned long)mysql_affected_rows(SQL));
return 0;
    } else {
        fprintf(stderr, "Delete error %d: %s\n", mysql_errno(SQL), mysql_error(SQL));
return -1;
    }
}


int mysqlClose()
{
if(SQL)
mysql_close(SQL);


return 0;
}

你可能感兴趣的:(嵌入式)