Check whether a table exists in the MySQL database in C.

Source: Internet
Author: User

Placeholder first, edit later

There are four ways to judge:

1. Show tables like 'testtable ';

This method is not easy to implement in the code.
2. SelectTABLE_NAMEFromINFORMATION_SCHEMA.TABLESWhereTABLE_SCHEMA= 'Dbname'
AndTABLE_NAME= 'Tablename'
;

This method is easy to implement. An instance that determines whether the testtable table exists in mybase:

MySQL; mysql_res * result = NULL; int COUNT = 0; If (0 = mysql_query (& MySQL, "select table_name from information_schema.tables where table_schema = 'mybase' and table_name = 'testtable'") {result = mysql_store_result (& MySQL); Count = mysql_num_rows (result );} else {printf ("error: % s \ n", mysql_error (& MySQL);} If (count> 0) printf ("This table already exists ");

3. Call mysql_list_tables (MySQL * MySQL, "tablename.

It is still used to determine whether there is a testtable instance in the mybase database currently connected:

MYSQL_RES *result=mysql_list_tables(&mysql,"testtable");MYSQL_ROW row;int count = 0;while((row=mysql_fetch_row(result))!=NULL){printf("TABLE %d: %s\n",cnt,row[0]);  cnt++;}if (mysql_errno(&mysql))  //mysql_fetch_row() failed due to an error{fprintf(stderr, "Error:%s\n",mysql_error(&mysql));}
If (count> 0) printf ("This table already exists ");

4. If the table does not exist, you can use the create table if not exists tablename command to create the table without querying whether the table exists.

You can also use APIs such as mysql_query.

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.