嗨,我正在尝试在我的项目中使用 C 连接 MySql,这是我第一次使用 C 和 MySql。我尝试在 MySql 中保存用户名、密码和角色。当我像这样运行程序时,没关系。
#include <mysql.h>
#include <stdio.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "admin"; /* set me first */
char *database = "profile";
char query[500];
memset(query,0,500);
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
int i =2;
/* send SQL query */
char userName[45] ="hi";
char userPassword[45];
char role[45];
strcpy(userName,"koko");
strcpy(userPassword,"hi");
strcpy(role,"admin");
sprintf(query,"insert into userTbl(name,password,role) values (\'%s\',\'%s\',\'%s\'); ",userName,userPassword,role);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
/* close connection */
mysql_close(conn);
}
尽管有一些警告,但我可以运行它而不会出现任何错误。但是当我使用函数编写这个程序时,我在编译它时遇到了这个错误。 用户'root'@'localhost'的访问被拒绝(使用密码:YES)
#include <mysql.h>
#include <stdio.h>
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "admin"; /* set me first */
char *database = "profile";
void saveUser(char * , char * ,char * );
void updateUser(char * , char * ,char * );
void showData();
main()
{
saveUser("kevin","hi","admin");
}
void saveUser(char *name, char *password,char *role)
{
char query[500];
memset(query,0,500);
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
int i =2;
/* send SQL query */
sprintf(query,"insert into userTbl(name,password,role) values (\'%s\',\'%s\',\'%s\'); ",name,password,role);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
res = mysql_use_result(conn);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
void updateUser(char *name, char *password,char *role)
{
char query[500];
memset(query,0,500);
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
printf("1234511\n");
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
int i =2;
/* send SQL query */
sprintf(query,"update userTbl set password=\'%s\',role=\'%s\' where name=\'%s\'; ",password,role,name);
if (mysql_query(conn, query)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(2);
}
/* close connection */
mysql_close(conn);
}
void showData()
{
/* output table name */
system("clear");
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
}
任何人都可以解释我哪里出错了,我该如何纠正它。我使用 gcc 来获取可执行文件并在命令提示符下运行它。提前致谢。
凯文