如何将数据插入mysql表? [英] How do I insert data into mysql table?

查看:76
本文介绍了如何将数据插入mysql表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的源代码,我尝试使用scanf / getchar读取字符串,但这不起作用。然后如何在读入程序后将数据插入mysql表(我在Linux中工作)



This is my source code and I've tried read strings with scanf/getchar, it wasn't work. Then how do I insert data into mysql table after read in program (I'm working in Linux)

#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>

static char *host = "localhost";
static char *user = "root";
static char *pass = "PASSWORD";
static char *dbname = "tutorial";

unsigned int port = 3306;
static char *unix_socket = NULL;
unsigned int flag = 0;

int main()
{
	MYSQL *conn;
	MYSQL_RES * res;
	MYSQL_ROW row;
	conn = mysql_init(NULL);

	if(!(mysql_real_connect(conn, host, user, pass, dbname, port, unix_socket, flag)))
	{
		fprintf(stderr, "Error: %s[%d]", mysql_error(conn), mysql_errno(conn));
		exit(1);
	}

	mysql_query(conn, "SELECT * FROM users");
	res = mysql_store_result(conn);
	

	while(row = mysql_fetch_row(res))
	{
		printf("%s\t%s\n", row[0], row[1]);
	}

	mysql_free_result(res);
	mysql_close(conn);
	
	return EXIT_SUCCESS;
}





我的尝试:



...

int id [1] = 5;

char name [8] =Jack;

...

mysql_query(conn,INSERT INTO用户(id,name)VALUES(id,name);

...



What I have tried:

...
int id[1] = 5;
char name[8] = "Jack";
...
mysql_query(conn, INSERT INTO users(id, name) VALUES(id, name);
...

推荐答案

好吧,你曾经说过你尝试过sql时发生的事情,虽然我会指出一些事情



a)mysql_query - 不,不是插入,你需要mysql_stmt_prepare和mysql_stmt_execute

b)你不显示你的表结构,但如果'id'是主键自动更新,你不应该把它包含在sql插件中声明



我看看这些引用(特别是第419页......在第一个引用插件时,带有绑定变量而不是连接的SQL)



http://www.kitebird。 com / mysql-book / ch06-3ed.pdf [ ^ ]



MySQL C API编程教程 [ ^ ]
Well, you havnt said what happened when you tried your sql, although I'd point out a couple of things

a) mysql_query - no, not for an insert, you need mysql_stmt_prepare and mysql_stmt_execute
b) you dont show your table structure, but if 'id' is a primary key auto updated, you should not include it in the sql insert statement

I'd have a look at these references (particularly page 419... in the first reference to do the insert, with binding variables and not concatenated SQL)

http://www.kitebird.com/mysql-book/ch06-3ed.pdf[^]

MySQL C API programming tutorial[^]


这篇关于如何将数据插入mysql表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆