VS2005 C 连接 MySql的步骤:
1.创建一个空的Win32控制台应用程序,取个名称mysql。
2.项目->mysql属性
2.1. 配置属性->C/C++->常规->附加包含目录 中填入”C:/Program Files/MySQL/MySQL Server 5.1/include“,注意这是在您的 mysql安装目录中*.lib文件的路径,建议mysql用“完整模式”来安装。
2.2. 配置属性->连接器->常规->附加库目录 中填入“C:/Program Files/MySQL/MySQL Server 5.1/lib/debug”
->附加依赖项 中填入"libmysql.lib"
->延迟加载的DLL 中填入"libmysql.dll;libmySQL.dll",注意这里必须要有“libmySQL.dll”;
2.3.在VS2005 窗体左侧的 “解决方案资源管理器中” 右键点中 “源文件” “添加新建项” 点选一下 “C++ 文件(.cpp)”我们输入代码文件名称“mysql.c” 点击“添加”;
2.4.将下面的代码拷贝到mysql.c文件中,把里面的用户名、密码等稍作调整,确保与您的相关设置是一致的。
2.5.生成->生成mysql(U)
2.6.调试->开始执行(不调试)
2.7.您已经可以看到从mysql中查询到的数据了。
2.8.致谢:感谢一个外国的家伙,抱歉我没记住您的名姓,下面的代码是从一个外国佬的博客中拷贝来的。
#include //这个是必须添加的,不然就会出现102个错误
#include
#include
#include
// just going to input the general details and not the port numbers
struct connection_details
{
char *server;
char *user;
char *password;
char *database;
};
MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
// first of all create a mysql instance and initialize the variables within
MYSQL *connection = mysql_init(NULL);
//MYSQL *connection, connect_data;
//connection = &connect_data;
// connect to the database with the details attached.
if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
printf("Conection error : %s/n", mysql_error(connection));
exit(1);
}
return connection;
}
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
// send the query to the database
if (mysql_query(connection, sql_query))
{
printf("MySQL query error : %s/n", mysql_error(connection));
exit(1);
}
return mysql_use_result(connection);
}
int main()
{
MYSQL *conn;// the connection
MYSQL_RES *res;// the results
MYSQL_ROW row;// the results row (line by line)
struct connection_details mysqlD;
//下面的四行,根据您的实际情况,可以适当做下调整
mysqlD.server = "localhost"; // where the mysql database is
mysqlD.user = "root";// the root user of mysql
mysqlD.password = "abc123456"; // the password of the root user in mysql
mysqlD.database = "mysql";// the databse to pick
// connect to the mysql database
conn = mysql_connection_setup(mysqlD);
// assign the results return to the MYSQL_RES pointer
res = mysql_perform_query(conn, "show tables");
printf("MySQL Tables in mysql database:/n");
while ((row = mysql_fetch_row(res)) !=NULL)
printf("%s/n", row[0]);
// clean up the database result set
mysql_free_result(res);
// clean up the database link
mysql_close(conn);
return 0;
}