2

我的表结构:

id int AUTO_INCREMENT PRIMARY KEY
title text
url text
age int

这是我尝试将数据保存到此表中的方式:

PreparedStatement ps=con.prepareStatement("insert into table(title, url, age) values ('\"+title+\",\"+url+\",\"+age+\"')");
System.out.println("Connected database successfully..");
ps.executeUpdate(); 

但是当我运行应用程序时,我得到

java.sql.SQLException:列计数与第 1 行的值计数不匹配

我想问题可能出在id列,如何解决?

4

3 回答 3

3

实际上,您有一个不同的问题(您只传递了一个“值”)-

PreparedStatement ps=con.prepareStatement("insert into table(title, url, age) "
    + "values (?,?,?)");
ps.setString(1, title);
ps.setString(2, url);
ps.setInt(3, age); // <-- at a guess!

您最初的查询将所有三个值放在一个字符串'\"+title+\",\"+url+\",\"+age+\"'中。

于 2013-12-30T19:25:40.933 回答
3

问题不在于id列。

从语句看来,您在所有列周围都有引号。因此,在 SQL 看来,您只有一列

'"title","url","age"'

你可能想要的是

"insert into table(title, url, age) values ('" + title + "','" + url + "'," + age + ")"

甚至更好,因为它是一个准备好的声明

"insert into table(title, url, age) values (?, ?, ?)"
于 2013-12-30T19:23:48.190 回答
0

可能的错误

  1. 你可能会被包括在内 + 额外签名
  2. 检查 DB 列顺序和 SQL 查询顺序
  3. 使用准备好的语句尝试相同的输入
  4. 检查数据库名称、表名、连接器

以下代码对我有用 -

try {
  Class.forName("com.mysql.jdbc.Driver");
  java.sql.Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ems","root","");
  java.sql.Statement s = c.createStatement();
  s.executeUpdate("INSERT INTO employee VALUES('','"+fullname+"','"+address+"','"+homephone+"','"+dob+"','"+mobile+"','"+martial+"','"+nic+"','"+title+"','"+department+"','"+basicsalary+"','"+nname+"','"+nrelationship+"','"+nmobile+"')");
  JOptionPane.showMessageDialog(rootPane, "Saved!");
} catch (ClassNotFoundException | SQLException ex) {
  Logger.getLogger(employeemanagement.class.getName()).log(Level.SEVERE, null, ex);
}
于 2021-04-03T03:53:01.993 回答