Simple MySQL ORM for C

Source: Internet
Author: User
Document directory
  • Simple MySQL ORM for C

Http://daoluan.net/blog? P = 1613

I never knew that there was such an ORM thing that I had to contact after talking with @ haipo.

In the project, you need to store data in the database. The first thought is to generate various raw SQL solutions. However, as the project progresses, it is found that it is not flexible. For example, if you want to add the dept_no field to the student table of the database because of new requirements, you need to modify it in various raw sq fields, which is a huge project. If you perform operations (insert, modify, or delete) on the data in the database table, you can perform many operations in the same way as operating on the data object to facilitate data layer changes without modifying the logic layer code.

// An insert statement to insert specified object data is extracted from the project. Int gtd_geninsertsql (struct task_t & toinsert, char * SQL, int nuserid) {int curr = 0; // task_id | user_id | strtext curr + = sprintf (SQL, "insert into task values (% d, % d, '% s',", toinsert. ID, nuserid/* user_id */, toinsert. strtext); // ctime char buffer [32];: memset (buffer, 0, sizeof (buffer); strftime (buffer, 32, "'1970-% m-% d % H-% m-% s',", & (toinsert. ctime); strncpy (SQL + curr, buffer, strlen (buffer); curr + = strlen (buffer );...... * (SQL + curr) = ')'; curr ++; return curr ;}

Orm, that is, object relationship ing. The ORM design is the design of the database persistence layer. Currently, mature ORM frameworks are available in various languages.

Because of the actual needs of the project, a lightweight framework is selected: simple MySQL ORM for C. Google only found an english blog article by the author of simple MySQL ORM for C: http://ales.jikos.cz/smorm /. I translated the article because it was not too long. I remember a few years ago, I mentioned that he had translated the excellent post on stackoverflow. Now, for example, if you are familiar with C ++, you can look at the foreign programmer community. On the one hand, you are a programmer, professional counterpart, recognize most words; on the other hand, there are many foreign experts, not a good opportunity to improve technology; finally, it is indeed a good way to improve English, like one.

The following is the simple MySQL ORM for, the original link: http://ales.jikos.cz/smorm/

Simple MySQL ORM for C

Author: alesak

C-version simple MySQL ORM is completed using Python scripts. It can be used to connect to the created MySQL database and read the data structure corresponding to the database table. Of course, you can also use this data structure and method to create a table. These enable developers to easily update, modify, and delete data in the database using the C language.

Previously, I needed to store and retrieve structured data in a powerful database. I prefer MySQL and C. However, I am bored with the rough code I wrote and the solution to the huge resources I found on the Internet, so I simply wrote one myself. Very simple, naive, rough (python is not the author's mother tongue, sorry ). However, I believe that Xi Shi appears in my lover's eyes, and I want to make it more useful. Also, documents about it...

This is just a technical article, not a user manual. I finally canceled the project mentioned in this article, so it remains to be tested. Some data types in MySQL are not supported. One of the reasons for this project is that I do not like the c api provided by MySQL, So I replaced it with a "more fashionable" everything-ready API ~ However, I found that it is not good enough in some places, because I have not completed it yet.

Let's get started. First, you must create your database table. I prefer this method, because only in this way can we make full use of the database.

CREATE DATABASE ex1;CREATE TABLE ex_customer (  id int NOT NULL auto_increment,  name char(32),  PRIMARY KEY  (id));CREATE TABLE ex_item (  customer_id int,  itemname char(32));

Next, we will create a simple Python script dB. py:

dbname = "ex1"name = "db"tables = { }

Next, let's execute it.

python rdb.py

Of course, it is less audible than the real rock. Maybe you will ask, How do I connect to the database? Of course, those are written by default ...... But let's look at our results. We can have two files generated: DB. h and DB. C. The former represents the data structure Declaration of the database table and the method for operating the data structure. The latter includes the definition of the method, followed by the Data initialization statement. Let's take a look:

typedef struct db_ex_customer {        int id;        char * name;} db_ex_customer;typedef struct db_ex_item {        int customer_id;        char * itemname;} db_ex_item;

I believe there is no need to further explain these things. Let's use them! The author created an ex1.c file. Note: To make it easier to read the code, I did not handle the returned error values:

#include <db.h>#include <stdio.h>#include <string.h>#include <time.h>int main (int argc, char **argv){int ret;MYSQL global_mysql;MYSQL *m;db_ex_customer *cust1;db_ex_item *item1, *item2;mysql_init (& global_mysql);/* * connect to MySQL as usual */m = mysql_real_connect (& global_mysql, "localhost", "root", "", "ex1", 3036, NULL, 0);/* * pass the MySQL connection to function, that initializes the "ORM" */ret = db_init (& global_mysql);/* * the *__new method creates empty structure */cust1 = db_ex_customer__new ();/* * setting the structure attribute with allocated string, * it will be freed during call of *__free method */cust1->name = strdup ("alesak");/* * this method inserts the structure into according table. * If it has serial field, its value is reflected into structure */ret = db_ex_customer__insert (cust1);item1 = db_ex_item__new ();/* * let's use the serial value from newly inserted customer */item1->customer_id = cust1->id;item1->itemname = strdup ("simple orm");ret = db_ex_item__insert (item1);item2 = db_ex_item__new ();item2->customer_id = cust1->id;item2->itemname = strdup ("advanced orm");ret = db_ex_item__insert (item2);db_ex_customer__free (cust1);db_ex_item__free (item1);db_ex_item__free (item2);return (0);}

Compile:

cc -I `mysql_config --cflags` ex1.c db.c `mysql_config --libs` -o ex1

Run the executable file and find that it is correct. This means that some data has been stored. At least if you comment on it, the author will say it is very elegant. Next, how can we retrieve the data? Suppose that we already know the key values recorded in the database table, and the author creates an ex2.c file.

#define _XOPEN_SOURCE 500#include <db.h>#include <stdio.h>#include <string.h>#include <time.h>int main (int argc, char **argv){int ret;MYSQL global_mysql;MYSQL *m;db_ex_customer *cust1;db_ex_item *item1, *item2;mysql_init (& global_mysql);m = mysql_real_connect (& global_mysql, "localhost", "root", "", "ex1", 3036, NULL, 0);ret = db_init (& global_mysql);cust1 = db_ex_customer__get_by_id (3);if (cust1) {fprintf (stdout, "I have customer named \'%s\'\n", cust1->name);db_ex_customer__free (cust1);}return (0);}

Compile and execute:

cc -I. `mysql_config --cflags` ex2.c db.c `mysql_config --libs` -o ex2./ex2

Finally, I don't want the ORM to automatically create related data queries, because I believe it can do well. (To be honest, if the default MyISAM is used, it is impossible to judge the relevant data ). Of course, next I want to create a select search that is connected to the ex_items table and ex_customer. Edit dB. py:

dbname = "ex1"name = "db"tables = {"ex_item" :[("get", "get_customer_items",[("INTEGER", "customer_id")], "SELECT ex_item.* FROM ex_item WHERE customer_id = ?")]}

Re-execute the DB. Puy script to add a new db_ex_item _ get_customer_items _ * method set. The flexibility of these methods is that you can add Integer Parameters to open a cursor on a specific SQL statement: Read a row of records from the cursor and close the cursor. We have extended ex2.c:

#define _XOPEN_SOURCE 500#include <db.h>#include <stdio.h>#include <string.h>#include <time.h>int main (int argc, char **argv){int ret;MYSQL global_mysql;MYSQL *m;db_ex_customer *cust1;db_ex_item *item1, *item2;mysql_init (& global_mysql);m = mysql_real_connect (& global_mysql, "localhost", "root", "", "ex1", 3036, NULL, 0);ret = db_init (& global_mysql);cust1 = db_ex_customer__get_by_id (3);if (cust1) {fprintf (stdout, "I have customer named \'%s\'..\n", cust1->name);db_ex_item__get_customer_items_open (cust1->id);while ((item1 = db_ex_item__get_customer_items_fetch ()) != NULL) {fprintf (stdout, ".. and found his item named \'%s\'\n", item1->itemname);db_ex_item__free (item1);}db_ex_item__get_customer_items_close ();db_ex_customer__free (cust1);}return (0);}

The result is as follows:

I have customer named 'alesak'.... and found his item named 'simple orm'.. and found his item named 'advanced orm'

Above, friends! Here is the http://ales.jikos.cz/smorm/rdb.py script. To be more specific, do not download this broken thing. If you like this idea, please tell me: alesak # gmail.com. The full text is complete.

Thank you for @ alesak. I have not personally tested simple MySQL ORM for C. I will try again later. In addition, the level of the author is limited. Welcome to help. Above.

3-22

Http://daoluan.net

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.