开发者

need advice on multiple database insert operations

I am writing a linux database application in C(mysql) and somewhere in my code, I need to execute a number of insert statements. suppose (for any reason) some of the inserts failed during the process. Is there an easy way to roll back? or the only way is to keep the track of insert statements.

thank you

by the way, the simplified piece of code and supporting structs is as follows:

#include <my_global.h>
#include <mysql.h>

#define MAX_RECORDS_FIELD_SIZE 150
#define MAX_RECORDS_VALUES_SIZE 300
typedef struct
{
    char connectionString[100];
    char  username[30];
    MYSQL *conn;
}connection;

typedef struct
{
    char  table_name[30];
    int nof_fields;
    void * fields;
    void * values;
}record;
typedef struct
{
    int nof_records;
    record *_record;
}records;
//this function can insert value into various records
int insert(connection _connection, records _records,void * _other)
{
    int i=0,j=0,m=0,n;
    char *str[100],fields[MAX_RECORDS_FIELD_SIZE],values[MAX_RECORDS_VALUES_SIZE];

    for(i=0;i<_records.nof_records;i++)
    {
        m=_records._record[i].nof_fields;
        if(m>0) sprintf(fields,"%s",_records._record[i]-&开发者_JAVA技巧gt;fields[0]);
        if(m>0) sprintf(fields,"%s",_records._record[i]->values[0]);
        for(j=1;j<m;j++)
        {
            sprintf(fields,"%s,%s",fields,_records._record[i]->fields[j]);
            sprintf(values,"%s,%s",fields,_records._record[i]->values[j]);
        }
        str[i]=calloc(1,sizeof(char)*(strlen(fields)+strlen(values)));
        sprintf(str[i],"insert into %s (%s) values(%s)",_records._record[i]->table_name,fields,values);
    }

    for(i=0;i<_records.nof_records;i++)
    {
        //do the insertion of str[i]
//      **error! what to do? how to roll back?**
        //free str[i]
    }

}


This is exactly what transactions were designed for. See:

  • http://en.wikipedia.org/wiki/Database_transaction
  • http://dev.mysql.com/doc/refman/5.6/en/sql-syntax-transactions.html


You have to disable autocommit and then you can use functions mysql_commit() and mysql_rollback() to commit/rollback your transaction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜