MySQL查询基于c中的用户输入

时间:2016-02-26 20:17:50

标签: mysql c

如何在c中从用户获取输入并在mysql语句的where子句中使用此输入

for k in o

2 个答案:

答案 0 :(得分:1)


char *input;
scanf("%s",input);

这是一个问题。 input只是指向某个地方的指针,它不是可以存储输入的实际缓冲区,并且它不会自动指向任何有意义的地方。您应该留出一个缓冲区来存储您的输入:

#define BUFFER_SIZE 20 // or however big you need your buffer to be
...
char input[BUFFER_SIZE + 1];
if ( fgets( input, sizeof input, stdin ) )
{
  /**
   * fgets doesn't strip the trailing newline
   */
  char *newline = strchr( input, '\n' );
  if ( newline )
    *newline = 0;

  // use input
}
else
{
  // error or EOF on input
}

scanf 是交互式输入的绝佳工具,而%s转换说明符会打开gets过去相同的安全漏洞 - 如果是用户比缓冲区更多的字符类型可以保存,然后C会很乐意将这些额外的字符存储到缓冲区后面的内存中,这可能会破坏重要的东西。

如果您的心脏使用scanf,那么您需要提供明确的最大输入大小作为%s说明符的一部分,例如%20s。不幸的是,这种最大输入大小必须以格式硬编码; scanf没有办法以printf的方式将其作为参数提供。您可以使用以下废话来解决它:

#define BUFFER_SIZE 20
#define STR(x) #x
#define FMT(len) "%" STR(len) "s"
...
scanf( FMT(BUFFER_SIZE), input );

它更容易使用fgets(并且fgets允许输入中有空格,而%s转换说明符将在第一个空白字符后停止读取) 。权衡是你必须处理尾随换行符。

mysql_quer(con,"select * from  where  = input ");

从不想要将用户输入直接传递给SQL语句;请参阅little Bobby Tables的比喻了解原因。您希望对输入进行一些完整性检查(确保至少没有';''''个字符。虽然它有点工作,但您可能想要使用准备好的声明 - here's an example

答案 1 :(得分:0)

使用<plugin> <groupId>net.alchim31.maven</groupId> <artifactId>scala-maven-plugin</artifactId> <version>3.2.0</version> <executions> <execution> <id>compile</id> <goals> <goal>compile</goal> </goals> <phase>process-resources</phase> </execution> <execution> <id>test-compile</id> <goals> <goal>testCompile</goal> </goals> <phase>process-test-resources</phase> </execution> </executions> <configuration> <scalaVersion>2.11.5</scalaVersion> </configuration> </plugin> 将输入变量插入SQL字符串。如果它是一个字符串,则值必须在引号中。此外,您从未为sprintf()分配空间。

input