MYSQL_ROW 和 row[0] 转换为字符串类型?
使用MYSQL C API查询结果时。 结果以 MYSQL_ROW
类型返回,根据 MYSQL C API 文档,我可以轻松 printf("%s", row[0])
。 但是如果我想将 row[0] 的内容传输到字符串或 char* 中怎么办?
When using MYSQL C API to query results. The results are returned as a MYSQL_ROW
type, which according to the MYSQL C API documentation, I can easily printf("%s", row[0])
. But what if I want to transfer the contents of row[0]
into a string or a char*?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
%s 格式应该只接受 char* 因此从你的描述看来 MYSQL_ROW 实际上是一个 char** 并且无论如何采用 row[0] 都会产生一个 char* 。
我不明白使用 sprintf() (或更安全但非标准的 asprintf())有什么好处,但如果它让您感觉更好,您可以考虑它。
The %s format is only supposed to accept char* so from your description it looks like MYSQL_ROW is really a char** and taking row[0] will yield a char* anyway.
I don't see how using sprintf() (or the safer but non standard asprintf()) would be of any benefit but you may consider it if it makes you feel better.
您可以使用 sprintf(),但您仍然需要知道字符串包含在 row[0] 中,以便您可以分配足够的内存。
警告:BCS 正确指出,如果 row[0] 包含额外的 nul 字节,您的数据将被截断。 如果您知道 row[0] 中存储了多少数据,请使用 memcpy() 可能是一个更好的解决方案。
You could use sprintf(), but you will still need to know the length of the string contained in row[0] so you can allocate enough memory.
Caveat: BCS correctly points out that your data will be truncated if row[0] contains extra nul bytes. If you know how much data is stored in row[0], using memcpy() is probably a better solution.
使用
mysql_fetch_lengths
确定MYSQL_ROW
中数组的长度。 因为行中有 1 个或多个列,所以可以有 1 个或多个长度。根据 27.8.5 C API 数据结构< /a> 文档:
然后,
mysql_fetch_row
< /a> 文档给出了这个例子:这是一个使用它来计算表中行数的示例。 该表是根据 FTC 的 Do 填充的没有通话违规。
Use
mysql_fetch_lengths
to determine the length of the array in theMYSQL_ROW
. Because there is 1 or more columns in the row, there can be 1 or more lengths.According to 27.8.5 C API Data Structures documentation:
Then, the
mysql_fetch_row
documentation gives this example:Here is an example of using it to count rows in a table. The table was populated from the FTC's Do No Call violations.