2

This is my code which is not working

    String sql="insert into user_master(User_Id,'First_Name','Last_Name','Address','City','Country','Email_Id',Cell_Number) values(DEFAULT,'"+fname+"','"+lname+"','"+address+"','"+city+"','"+country+"','"+email+"',"+cellno+")";

This one is working fine

    String sql="insert into user_master values(1,'"+fname+"','"+lname+"','"+address+"','"+city+"','"+country+"','"+email+"',"+cellno+")";

But I don't want to increment id every time, I have already used serial type as i specified. But with DEFAULT it's not working.

Any idea?

6
  • You should really be using a prepared statement. Commented Mar 4, 2013 at 19:26
  • With that it will be working fine? Commented Mar 4, 2013 at 19:28
  • No, I just meant that without it your code is susceptible to SQL injection attacks. Commented Mar 4, 2013 at 19:30
  • Ya. Thanks @David Conrad. Any idea where am lacking in the code? Commented Mar 4, 2013 at 19:33
  • Sorry, I'm not that familiar with postgresql. What happens if you simply omit all reference to the User_Id column? I'm guessing it's the primary key; is it set up to autoincrement? Commented Mar 4, 2013 at 19:36

1 Answer 1

2

Use named columns, and omit the one you want to have defaulted:

String sql="insert into user_master(first_name,last_name,address,city,country,email_id,cell_number) values('"+fname+"','"+lname+"','"+address+"','"+city+"','"+country+"','"+email+"',"+cellno+")";

This will solve your problem, but you should still use a prepared statement as mentioned above for other reasons (SQL injection, quoting issues, etc).

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for reply. Still its not working. With error ERROR: syntax error at or near "'First_Name'"
Now following error appear ERROR: column "first_name" of relation "user_master" does not exist. Even though Column First_Name is there in table user_master.
This might be due to the way you created your table if you quoted your columns when you created the table, the case might be different. Verify how it looks in the database, and try using double quotes around the column names: "First_Name","Last_Name". Also make sure to escape the double quotes in Java.
No they are the same. But i fixed the problem by converting all the fields to lower case. May be that means postgresql support lower case fields names.
Did you convert the fields in your java code or in the database table? By default postgresql field names are not case sensitive, but if you declare them inside double quotes, they will be case sensitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.