Home Database Mysql Tutorial C连接MySQL数据库开发之Linux环境完整示例演示(增、删、改、查_MySQL

C连接MySQL数据库开发之Linux环境完整示例演示(增、删、改、查_MySQL

Jun 01, 2016 pm 01:13 PM
include linux mysql Database development

一、开发环境

ReadHat6.332位、mysql5.6.15、gcc4.4.6

二、编译

gcc-I/usr/include/mysql-L/usr/lib-lmysqlclient main.c -o main.out

-I:指定mysql头文件所在目录(默认去/usr/include目录下寻找所用到的头文件)

-L:指定mysql动态库文件所在目录(默认从/usr/lib目录查找)

-l:链接libmysqlclient.so动态库

-o:生成的可执行文件名

三、完整示例

1

////main.c//mysql数据库编程////Created by YangXin on 14-5-22.//Copyright (c) 2014年 yangxin. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <mysql.h>MYSQL mysql;// 查询int query();// 修改int update();// 添加数据my_ulonglong add();// 参数化添加数据my_ulonglong addByParams();// 删除数据my_ulonglong delete();// 打印数据库服务器信息void printMySqlInfo();int main(int argc, const char * argv[]){   /*连接之前,先用mysql_init初始化MYSQL连接句柄*/   mysql_init(&mysql);     /*使用mysql_real_connect连接服务器,其参数依次为MYSQL句柄,服务器IP地址,   登录mysql的用户名,密码,要连接的数据库等*/  if(!mysql_real_connect(&mysql, "localhost", "root", "yangxin", "test", 0, NULL, 0)) {       printf("connecting to Mysql error:%d from %s/n",mysql_errno(&mysql), mysql_error(&mysql));      return -1;  }else {     printf("Connected Mysql successful!/n");    }       printMySqlInfo();       // 设置编码 mysql_query(&mysql, "set names utf8");      // 参数化添加数据  addByParams();      // 查询   query();        // 修改   update();       // 添加   add();      // 删除   delete();       /*关闭连接*/    mysql_close(&mysql);    return 0;}// 查询int query(){ int flag, i;    const char *sql = NULL; MYSQL_RES *res = NULL;  MYSQL_ROW row = NULL;   MYSQL_FIELD *fields = NULL; sql = "select * from t_user" ;  flag = mysql_real_query(&mysql, sql, (unsigned int)strlen(sql));    if (flag) {     printf("query error:%d from %s/n",mysql_errno(&mysql),mysql_error(&mysql));     return -1;  }        // 将查询结果读取到内存当中,如果数据很多的情况会比较耗内存    res = mysql_store_result(&mysql);   // res = mysql_use_result(&mysql); // 需要用到的时候,每次从服务器中读取一行       // 字段数量 unsigned int field_count = mysql_field_count(&mysql);   printf("field_cout:%d/n",field_count);      // 查询总数 my_ulonglong rows = mysql_num_rows(res);    printf("%lld/n",rows);      // 获取所有字段   fields = mysql_fetch_fields(res);   for (int i = 0; i  10"; flag = mysql_real_query(&mysql, sql, strlen(sql));  if (flag) {     printf("delete data error:%d from %s/n",mysql_errno(&mysql), mysql_error(&mysql));      return -1;  }       my_ulonglong affected_rows = mysql_affected_rows(&mysql);   printf("删除的行数:%lld/n",affected_rows);       printf("success delete %lld record data !/n",affected_rows);    return affected_rows;}void printMySqlInfo(){    const char *stat = mysql_stat(&mysql);  const char *server_info = mysql_get_server_info(&mysql);    const char *clientInfo = mysql_get_client_info();   unsigned long version = mysql_get_client_version(); const char *hostinfo =  mysql_get_host_info(&mysql);    unsigned long serverversion = mysql_get_server_version(&mysql); unsigned int protoinfo = mysql_get_proto_info(&mysql);      printf("stat:%s/n",stat);   printf("server_info:%s/n",server_info); printf("clientInfo:%s/n",clientInfo);   printf("version:%ld/n",version);    printf("hostinfo:%s/n",hostinfo);   printf("serverversion:%ld/n",serverversion);    printf("protoinfo:%d/n",protoinfo);     const char *charactername = mysql_character_set_name(&mysql);   printf("client character set:%s/n",charactername);  if (!mysql_set_character_set(&mysql, "utf8"))   {       printf("New client character set: %s/n",             mysql_character_set_name(&mysql)); }}</mysql.h></string.h></stdlib.h></stdio.h>

Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

How to copy and paste mysql How to copy and paste mysql Apr 08, 2025 pm 07:18 PM

Copy and paste in MySQL includes the following steps: select the data, copy with Ctrl C (Windows) or Cmd C (Mac); right-click at the target location, select Paste or use Ctrl V (Windows) or Cmd V (Mac); the copied data is inserted into the target location, or replace existing data (depending on whether the data already exists at the target location).

How to view mysql How to view mysql Apr 08, 2025 pm 07:21 PM

View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

Master SQL LIMIT clause: Control the number of rows in a query Master SQL LIMIT clause: Control the number of rows in a query Apr 08, 2025 pm 07:00 PM

SQLLIMIT clause: Control the number of rows in query results. The LIMIT clause in SQL is used to limit the number of rows returned by the query. This is very useful when processing large data sets, paginated displays and test data, and can effectively improve query efficiency. Basic syntax of syntax: SELECTcolumn1,column2,...FROMtable_nameLIMITnumber_of_rows;number_of_rows: Specify the number of rows returned. Syntax with offset: SELECTcolumn1,column2,...FROMtable_nameLIMIToffset,number_of_rows;offset: Skip

Can I retrieve the database password in Navicat? Can I retrieve the database password in Navicat? Apr 08, 2025 pm 09:51 PM

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

See all articles