0

I have the following code to input data into the database using java. However, first column is actually generated automatically by postgresql database. Now, how would I change the code so it does not touch the first column?

String sql = "insert into members values (?,?,?,?)";
            PreparedStatement pst = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // I used RETURN_GENERATED_KEYS, but I don't know how to utilize it.
            pst.setInt(1, memid); // I want this line to be skipped
            pst.setInt(2, birthyear);
            pst.setString(3, familyname);
            pst.setString(4, givenname);
            // Executing the insert
            pst.executeUpdate();

2 Answers 2

2

Include the list of fields you want to insert in the SQL:

insert into members (birthyear, familyname, givenname) values (?,?,?)

This way the value for the first column will have its default (auto-generated) value.

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

5 Comments

null value in column "memid" violates not-null constraint
is the memid column set to serial?
make sure "memid" is autogenerated column
oh i see, nextval('cag.mem_memid_seq'::regclass) was not set in memid
thank you very much. could you be able to check my other question about searching from database please?
0

suppose i have two column named "name", "email" , then i can use this code to insert values to the database containing table( std_tb) with two column

String s_name="ayman";
String s_email="mamstricks"; 
PreparedStatement ps=con.prepareStatement("insert into std_tb(name,mail) values(?,?)");   
ps.setString(1, s_name); 
ps.setString(2, s_email); 
ps.executeUpdate();

if i want to insert second column only, then i can use this code to same table containing two column

String s_email="ayman"; 
PreparedStatement ps=con.prepareStatement("insert into std_tb(mail) values(?)");  
ps.setString(1, s_email);
ps.executeUpdate();

but don't forget to set first column with null value , if you are using wamp or xampp then ,you can do this by going "http://localhost/phpmyadmin/" then access to your table then put tick mark on null box

Comments

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.