用C语言怎么实现与数据库的连接

Python020

用C语言怎么实现与数据库的连接,第1张

#include<mysql/mysql.h>

#include<stdio.h>

intmain()

{

MYSQL*conn

MYSQL_RES*res

MYSQL_ROWrow

char*server="localhost"//本地连接

char*user="root"//

char*password="525215980"//mysql密码

char*database="student"//数据库

char*query="select*fromclass"//需要查询的语句

intt,r

conn=mysql_init(NULL)

if(!mysql_real_connect(conn,server,user,password,database,0,NULL,0))

{

printf("Errorconnectingtodatabase:%s\n",mysql_error(conn))

}else{

printf("Connected...\n")

}

t=mysql_query(conn,query)

if(t)

{

printf("Errormakingquery:%s\n",mysql_error(conn))

}else{

printf("Querymade...\n")

res=mysql_use_result(conn)

if(res)

{

while((row=mysql_fetch_row(res))!=NULL)

{

//printf("num=%d\n",mysql_num_fields(res))//列数

for(t=0t<mysql_num_fields(res)t++)

printf("%8s",row[t])

printf("\n")

}

}

mysql_free_result(res)

}

mysql_close(conn)

return0

}

扩展资料

C语言使用注意事项:

1、指针是c语言的灵魂,一定要灵活的使用它:

(1)、指针的声明,创建,赋值,销毁等

(2)、指针的类型转换,传参,回调等

2、递归调用也会经常用到:

(1)、递归遍历树结构

(2)、递归搜索

用数据结构组织起来就是简单的数据库了,无非就是插入删除修改之类的功能

你说的那些数据库语句,可以用简单的字符串匹配来做

如:strcmp 匹配"Create table"这个字符串 对接下来字符进行提取,直到"(" 以后的关键字符也是用类似方法判断","等实现

提取了需要的关键字符之后就可以进行对应的传参,调用相应操作