Embed SQL into c to operate PostgreSQL

Source: Internet
Author: User
In the past two days, due to project reasons, I had a little bit of confidence and learned how to embed SQL into PostgreSQL in C. I wrote a small example, including connecting to the database and creating tables, for more information, see PostgreSQL8.0 Chinese manual.

You can use a text editor to write data. pgc file, and then use the ecpg in the bin under the PostgreSQL installation directory to put. pgc file generation. c file, and then use the c compiler to generate the corresponding executable program. On windows, I use VC ++. If the header file or lib cannot be found during compilation, the include directory and lib directory under the PostgreSQL installation directory can be introduced.

The following is the code of the. pgc file. The generated. c file is long and will not be written.

Int main (int argc, char * argv [])

{

Exec SQL CONNECT TO servername@192.168.2.5 USER username/password;

Exec SQL INCLUDE SQLCA;

If (sqlca. sqlcode)

{

Printf ("Connect failed \ n"); // connection failed

}

Else

{

Exec SQL BEGIN DECLARE SECTION;

Char ascii [16 + 1]; // on my system, if no 1 is added, garbled characters will appear after printing on the console.

Exec SQL END DECLARE SECTION;

Printf ("Connect success \ n ");

// Create a table

Exec SQL CREATE TABLE foo (number integer, ascii char (16 ));

Exec SQL CREATE UNIQUE INDEX num1 ON foo (number );

Exec SQL COMMIT;

Printf ("Table Created \ n ");

// Insert data

Exec SQL INSERT INTO foo (number, ascii) VALUES (9999, 'doodad ');

Exec SQL COMMIT;

Printf ("Inserted \ n ");

// Query

Exec SQL SELECT ascii INTO: ascii FROM foo WHERE number = 9999;

Printf ("ascii = % s \ n", ascii );

}

Exec SQL DISCONNECT; // close the connection

Return 0;
}

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.