MySQL C程序mysql连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3453168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C program mysql connection
提问by Mats Stijlaart
I'm working on a simple c program that has to connect to my database, then do a query and then close the connection.
我正在开发一个简单的 c 程序,它必须连接到我的数据库,然后执行查询,然后关闭连接。
int main()
{
MYSQL *conn;
conn = mysql_init(NULL);
if (conn == NULL) {
printf("Error %u %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_real_connect(conn, "localhost", "root", "root", NULL, 8889, NULL, 0)) {
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
if (mysql_query(conn, "create database testdb")) {
printf("Error %u: %s",mysql_errno(conn), mysql_error(conn));
exit(1);
}
mysql_close(conn);
return 0;
}
This code compiles but when I run it, it will exit after the mysql_query()
statement.
此代码编译但当我运行它时,它将在mysql_query()
语句后退出。
The following error is returned:
返回以下错误:
Error 2006: MySQL server has gone away
I used google to search for an answer and ended up here:
我用谷歌搜索答案,结果在这里:
采纳答案by user376258
Return Values
A MYSQL* connection handle if the connection was successful, NULL if the connection was unsuccessful. For a successful connection, the return value is the same as the value of the first parameter.
返回值
如果连接成功则为 MYSQL* 连接句柄,如果连接不成功则为 NULL。对于成功连接,返回值与第一个参数的值相同。
http://dev.mysql.com/doc/refman/5.0/en/mysql-real-connect.html
http://dev.mysql.com/doc/refman/5.0/en/mysql-real-connect.html
your connection is not being made
你的连接没有建立
回答by KumarA
/* Simple C program that connects to MySQL Database server*/
/* 连接 MySQL 数据库服务器的简单 C 程序*/
#include <mysql.h>
#include <stdio.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "PASSWORD"; /* set me first */
char *database = "mysql";
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);
}
/* send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
回答by David Knell
Your connection's failing - your test should be:
您的连接失败 - 您的测试应该是:
if (mysql_real_connect(...) == NULL) {
printf("...");
exit(1);
}
mysql_real_connect returns NULL on failure, or the connection handle on success.
mysql_real_connect 失败时返回 NULL,成功时返回连接句柄。
--Dave
--戴夫