2

The structure of my table:

id int AUTO_INCREMENT PRIMARY KEY
title text
url text
age int

Here's how I am trying to save data into this table:

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

But when I run the app, I get

java.sql.SQLException: Column count doesn't match value count at row 1

I guess the problem might be in the id column, how to solve it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user984621
  • 46,344
  • 73
  • 224
  • 412
  • Did you try printing out your prepared statement string fist and make sure it is formatted correctly? Also, should be using parameters. – OldProgrammer Dec 30 '13 at 19:23
  • Ugh. I see this so often it's mind boggling. What DBMS are you using? It can not be SQLServer and mySQL. It's one or the other. – Zane Dec 30 '13 at 19:42

3 Answers3

3

The problem is not the id column.

From the statement it looks like you have quotes around all columns. Therefore it seems to the SQL, that you have only one column

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

What you might want to have is

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

or even better yet, since it is a prepared statement

"insert into table(title, url, age) values (?, ?, ?)"
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
3

Actually, you have a different problem (you're only passing one "value") -

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!

You original query put all three values in one string '\"+title+\",\"+url+\",\"+age+\"'.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

possible mistakes

  1. you may be included + sign extra
  2. check the DB column order and SQL query order
  3. try the same input with prepared statement
  4. check the DB name,table name,connecter

The following code worked for me -

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);
}
EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
Naveen S
  • 101
  • 1
  • 3