我创建了一个表,但是在插入值时出错了。在插入时,[]是我传递给函数的字符串数组。我收到以下错误:
Column count doesn't match value count at row 1
这是我的代码:
try
{
String tablename=c+d;
String ab="";
for(int i=1 ; i<=k ; i++)
{
ab =ab+"column"+i+" VARCHAR(255),";
}
//establish connection to database
connection = DriverManager.getConnection(DATABASE_URL,"root","rohma");
statement = connection.createStatement();
//resultSet = statement.executeQuery("SELECT idactors,firstname,lastname FROM actors");
String sql ="CREATE TABLE " + tablename + "(id INTEGER not NULL AUTO_INCREMENT, " + ab + " PRIMARY KEY ( id ))";
statement.executeUpdate(sql);
int ki=0;
//
String abv ="";
String tv="";
int gk =1;
for(int i =0 ; i<k ;i++)
{
// colum shows i and j shows fieds insertion
for(int j=0 ; j<p ; j++)
{
if(j<p-1)
{
abv =abv +"'"+a[ki]+"'"+"," ;
ki++;
}
else
{
abv =abv +"'"+a[ki]+"'";
ki++;
}
}
tv ="INSERT INTO `abc`.`"+tablename+"` (`column "+gk+"`) VALUES ("+abv+")";
gk++;
statement.executeUpdate(tv);
}
}
答案 0 :(得分:3)
使用以下命令创建列名称:
ab =ab+"column"+i+" VARCHAR(255),";
但是当您执行插入操作时,代码中的单词列后面会有一个空格:
INSERT INTO `abc`.`"+tablename+"` (`column "+gk+"`)
它应该是这样的:
INSERT INTO `abc`.`"+tablename+"` (`column"+gk+"`)
您可以在创建表时和执行SQL之前添加打印输出,以确保列数与插入VALUES的数量相同。还要确保插入中的列与创建的列相同。
答案 1 :(得分:1)
创建表时,您可以:
for(int i=1 ; i<=k ; i++) {
ab =ab+"column"+i+" VARCHAR(255),";
}
但是当你准备插入时,你会这样做:
for(int i =0 ; i<k ;i++) {
...
ded = ded+"`column"+gk+"`,";
...
}
所以你的问题是用于列名的不同索引。
尝试:
for(int i =1 ; i<=k ;i++) {
...
ded = ded+"`column"+i+"`,";
...
}