今天在写一个程序时发现一个奇异的现象。
注意其中的float ssavg_ap[4]; float ssdev_ap[4]; 当我把它两放在main函数外面作全局变量时,程序编译没问题,但执行时就出现如下错误:
Inset error 1064:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near ' ( p-) pM) u-) p-) ' at line 1
起初我以为是我float变量的精度问题,或是SQL语句错误,或是计算错误。后来我把上述两句声明放到main函数里面,奇迹般的就插入成功了,
实在想不通这是为什么,这点小问题实在是难以发现。
Code
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include "mysql.h"
float scan_data[20][4];
float position_x,position_y;
// float ssavg_ap[4];
// float ssdev_ap[4];
int main(int argc,char *argv[]){
MYSQL my_connection;
int res;
int id=19;
float position[2];
float ssavg_ap[4];
float ssdev_ap[4];
printf("输入测试点地坐标:\n");
printf("X: ");
scanf("%f",&position[0]);
printf("Y: ");
scanf("%f",&position[1]);
printf("测试点地坐标为(%f,%f)\n",position[0],position[1]);
int i,j;
for(i=0;i<20;i++) //暂时赋值
for(j=0;j<4;j++)
scan_data[i][j]=1;
for(i=0;i<20;i++){
for(j=0;j<4;j++)
printf("%f ",scan_data[i][j]);
printf("\n");
}
float s,d;
for(j=0;j<4;j++){
s=0;d=0;
for(i=0;i<20;i++){
s+=scan_data[i][j];}
ssavg_ap[j]=s/20;
printf("%d的平均值是: %f\n",j,ssavg_ap[j]);
for(i=0;i<20;i++)
d+=(scan_data[i][j]-ssavg_ap[j])*(scan_data[i][j]-ssavg_ap[j]);
ssdev_ap[j]=sqrt(d/20);
printf("%d地标准差是: %f\n",j,ssdev_ap[j]);
}
char sqlstr[100];
sprintf(sqlstr,"INSERT INTO point VALUES(%d,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f)",id,position[0],position[1],ssavg_ap
[0],ssavg_ap[1],ssavg_ap[2],ssavg_ap[3],ssdev_ap[0],ssdev_ap[1],ssdev_ap[2],ssdev_ap[3]);
printf("%s\n",sqlstr);
mysql_init(&my_connection);
if(mysql_real_connect(&my_connection,"localhost","root","123456","dw",0,NULL,0)){
printf("Connection success\n");
res=mysql_query(&my_connection,sqlstr);
if(!res){
printf("Inserted %lu rows\n",(unsigned long)mysql_affected_rows(&my_connection));
}else{
fprintf(stderr,"Inset error %d: %s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
}
mysql_close(&my_connection);
}else{
fprintf(stderr,"Connection failed\n");
if(mysql_errno(&my_connection)){
fprintf(stderr,"Connection error %d:%s\n",mysql_errno(&my_connection),mysql_error(&my_connection));
}
}
return EXIT_SUCCESS;
}