MySQL
关于C语言编程与MySQL数据库的简单连接代码
#include <my_global.h>
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
static const char* host = "localhost";
static const char* user = "root";
static const char* password = "123456";
static const char* database = "Goods";
//判断函数 连接错误报错返回
static void finish_with_error(MYSQL * con)
{
fprintf(stderr,"MySQL 执行错误:%s\n",mysql_error(con));
if(con)
{
mysql_close(con);
}
exit(EXIT_FAILURE);
}
int main(int argc,char* argv[])
{
if(argc < 2)
{
fprintf(stderr,"必须指定姓名\n");
return EXIT_FAILURE;
}
//创建MySQL结构
//MYSQL *mysql_init(MYSQL *mysql)
//分配初始化适用于mysql_real_connect()的MYSQL对象。
//若是没有足够的空间则为NULL
MYSQL *con = mysql_init(NULL);
if (con == NULL)
{
finish_with_error(con);
}
//连接数据库
//建立与数据库引擎的连接
//mysql_real_connect()
// MYSQL *mysql_real_connect(MYSQL *mysql, const char *host, const char *user,
// const char *passwd, const char *db, unsigned int port,
// const char *unix_socket, unsigned long client_flag)
// MYSQL *mysql 第一个参数是指定现有数据库结构的地址
// const char *host 这里可能是一个主机名(localhost)\.(本地)\是一个IP地址
// const char *user 数据库用户名
// const char *passwd 数据库用户的密码
// const char *db 使用的数据库
// unsigned int port 若是值不为0则是作为TCP/IP连接端口
// const char *unix_socket 若是不为NULL则是指明要使用套接字或者命名管道
// unsigned long client_flag 通常为0,但是可以作为一些标志组合
if(mysql_real_connect(con, host, user, password, database,0,NULL,0) == NULL)
{
finish_with_error(con);
}
//设置客户端字符编码为 UTF-8
//设置当前连接的默认字符集
//int mysql_set_character_set(MYSQL *mysql, const char *csname)
// MYSQL *mysql 第一个参数是指定现有数据库结构的地址
// const char *csname 设置字符集的类型
if(mysql_set_character_set(con,"utf8") != 0)
{
finish_with_error(con);
}
char query[1000];
sprintf(query,"select * from goods where goods_name = '%s'",argv[1]);
printf("拼接出的 SQL : %s\n",query);
//执行SQL
//执行*stmt_str所指向的SQL语句
//int mysql_query(MYSQL *mysql, const char *stmt_str)
// MYSQL *mysql 第一个参数是指定现有数据库结构的地址
// const *stmt_str 指向SQL语句
if(mysql_query(con,query))
{
finish_with_error(con);
}
//获取查询结果,select 相关操作必须将结果用掉
//使用在 mysql_query()或者mysql_real_query()之后调用查询结果,结果集。
//使用完之后必须使用 my_free_query()
//MYSQL_RES *mysql_store_result(MYSQL *mysql)
// MYSQL *mysql 第一个参数是指定现有数据库结构的地址
//
MYSQL_RES *result = mysql_store_result(con);
if(result == NULL)
{
finish_with_error(con);
}
//返回结果集列数
//unsigned int mysql_num_fields(MYSQL_RES *result)
// MYSQL_RES *result 结果集
int num_fields = mysql_num_fields(result);
printf("列数: %d\n",num_fields);
//分别打印每一行
//检索结果集的下一行
//MYSQL_ROW mysql_fetch_row(MYSQL_RES *result))
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{
unsigned long* lengths;
lengths = mysql_fetch_lengths(result);
for(int i = 0;i < num_fields; ++i)
{
printf("[%.*s]",(int)lengths[i], row[i] ? row[i] : "NULL");
}
printf("\n");
}
//释放为结果集创建的内存
//void mysql_free_result(MYSQL_RES *result)
mysql_free_result(result);
//关闭数据库服务连接
//void mysql_close(MYSQL *mysql))
mysql_close(con);
}