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

用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)、递归搜索

C#连接数据库有以下几个步骤:

1:使用配置的数据库连接串,创建数据库连接 Connection 对象

2:构建 *** 作的sql语句

3:定义command对象

4:打开数据连接

5:执行命令

举一个例子,删除 *** 作

public class StudentService

{

//从配置文件中读取数据库连接字符串

private readonly static string connString = ConfigurationManager.ConnectionStrings["accpConnectionString"].ToString()

private readonly static string dboOwner = ConfigurationManager.ConnectionStrings["DataBaseOwner"].ToString()

AdoNetModels.Student model = new Student()

#region 删除数据1

public int DeleteStudent(int stuID)

{

int result = 0

// 数据库连接 Connection 对象

SqlConnection connection = new SqlConnection(connString)

// 构建删除的sql语句

string sql = string.Format("Delete From Student Where stuID={0}", stuID)

// 定义command对象

SqlCommand command = new SqlCommand(sql, connection)

try

{

connection.Open()

result = command.ExecuteNonQuery() // 执行命令

}

catch (Exception ex)

{

Console.WriteLine(ex.Message)

}

finally

{

connection.Close()

}

return result

}

#endregion


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/7737259.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-09
下一篇 2023-04-09

发表评论

登录后才能评论

评论列表(0条)

保存