Table of Contents
首先保证安装:
C语言连接MySQL数据库
错误处理
Home Database Mysql Tutorial Linux下C语言连接MySQL_MySQL

Linux下C语言连接MySQL_MySQL

Jun 01, 2016 pm 01:26 PM
c language include linux database

bitsCN.com

首先保证安装:

1:安装MySQL:sudo apt-get install mysql-server mysql-client 2:安装MySQL开发包:sudo apt-get install libmysqlclient15-dev 此时需要用到的头文件会出现在/usr/include/mysql/里

C语言连接MySQL数据库

此包含两个步骤: 1. 使用函数mysql_init初始化一个连接句柄结构. mysql_init的函数定义如下:
MYSQL * mysql_init(MYSQL *);
Copy after login
通常传递NULL给这个例程,他会返回一个指向新分配的连接句柄结构的指针。如果传递一个已有的结构,它将会重新初始化。这个例程在出错时返回NULL.

2. 实际进行连接 目前只是分配和初始化了一个结构,仍然需要使用mysql_real_connect来向一个连接提供参数,
mysql_real_connect的函数定义:
MYSQL* mysql_real_connect(MYSQL* connection,		const char *server_host,		const char *sql_user_name,		const char *sql_password,		const char *db_name,		unsigned int port_number,		const char *unix_socket_name,		unsigned int flags);
Copy after login

指针connection必须指向已经被mysql_init初始化过的结构。

注意server_host既可以是主机名,也可以是IP地址。如果连接本地,可以制定localhost来优化。

sql_user_name和sql_password的含义和它们的字面意思一样。如果登录名为NULL,则假设登录名为当前Linux用户的登录ID,如果密码为NULL,则假设密码为空。

port_number和unix_socket_name应该分别为0和NULL,除非你改变了MySQL安装的默认设置。他们将默认使用合适的值。

最后,flags参数用来对一些定义的位模式进行OR操作,使得改变使用协议的某些特性。

如果无法连接,则返回NULL。mysql_error函数可以提供有帮助的信息。

3. 使用完连接,通常在程序退出前,要调用函数mysql_close;

mysql_close的函数定义:

void mysql_close(MYSQL *connection);
Copy after login
将关闭连接。

连接MySQL的示例:
#include <stdio.h>#include <stdlib.h>#include "mysql.h"int main (int argc, char *argv[]) {	MYSQL *conn;	// 步骤1: 初始化连接句柄	conn = mysql_init(NULL);	if (conn == NULL) { // 如果返回NULl说明初始化失败		printf("mysql_init failed!/n");			return EXIT_FAILURE;	}	// 步骤2:实际进行连接	// 参数分别为,conn连接句柄,host是MySQL所在主机或地址,user用户名,password密码,database_name数据库名,后面的都是默认	conn = mysql_real_connect(conn, "host", "user", "password", "database_name", 0, NULL, 0);	if (conn) { // 连接成功		printf("Connection success!/n");		} else {		printf("Connection failed!/n");		}	// 步骤3: 退出前关闭连接	mysql_close(conn);	return 0;}
Copy after login

编译和运行:
gcc -I/usr/include/mysql test.c -L/usr/lib/mysql -lmysqlclient -o app
Copy after login
/

错误处理

错误处理的两个函数:

// 返回错误码unsigned int mysql_errno(MYSQL *connection);// 返回错误详细信息char* mysql_error(MYSQL *connection);
Copy after login
注意,当调用conn = mysql_real_connect(...), 时会遇到一个问题,因为它在失败时返回NULL指针,并没有提供一个错误码。但如果是将句柄作为一个变量,那么即使mysql_real_connect失败,也仍然能够处理它。
#include <stdio.h>#include <stdlib.h>#include "mysql.h"#include "errmsg.h"#include "mysqld_error.h"void Error(MYSQL* conn) {	printf("Connection error %d: %s/n", mysql_errno(conn), mysql_error(conn));}int main (int argc, char *argv[]) {	MYSQL conn; // 是变量而不是指针	mysql_init(&conn); // 注意取地址符&	if (mysql_real_connect(&conn, "192.168.137.246", "root", "123456", "test", 0, NULL, 0)) {		printf("Connection success!/n");		mysql_close(&conn);	} else {		fprintf(stderr, "Connection failed!/n");		if (mysql_errno(&conn)) {			fprintf(stderr, "Connection error %d: %s/n", mysql_errno(&conn), mysql_error(&conn));		}	}	return EXIT_SUCCESS;}
Copy after login
bitsCN.com
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

What is the main purpose of Linux? What is the main purpose of Linux? Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

See all articles