In my last post related with JDBC I mentioned only about creating tables and inserting new values to a database file using SQL statements. According to comments left by visitors today I am going to post on updating and deleting a particular record. For update or deletion of a record you will have tobe sure that the particular record actually exists in database. If this condition is not checked and you try to modify a non-existing record then you will get a run-time exception. So to avoid this first search for this record using an id(which must be unique) as below written code :
Statement stmt=con.createStatement(); //con is Connection object
ResultSet rs=stmt.executeQuery("SELECT Roll FROM Records"); //Roll is the unique id
int an=0;
boolean found=false;
while(rs.next() && found==false){
an=rs.getInt(0); //0 as Roll. is the first column
if(an==Integer.parseInt(enter_id)) //enter_id is input id
found=true; //if id is found in database
}
Now you can modify or delete using id if found is true like below shown code :
if(found) //then do anyone of below
stmt.execute("UPDATE Records SET Sname="+n+" WHERE Roll="+enter_id); //for changing a value
stmt.execute("DELETE Records WHERE Roll="+enter_id); //for deleting a record
Read this first -->Java program to connect to a database
Statement stmt=con.createStatement(); //con is Connection object
ResultSet rs=stmt.executeQuery("SELECT Roll FROM Records"); //Roll is the unique id
int an=0;
boolean found=false;
while(rs.next() && found==false){
an=rs.getInt(0); //0 as Roll. is the first column
if(an==Integer.parseInt(enter_id)) //enter_id is input id
found=true; //if id is found in database
}
Now you can modify or delete using id if found is true like below shown code :
if(found) //then do anyone of below
stmt.execute("UPDATE Records SET Sname="+n+" WHERE Roll="+enter_id); //for changing a value
stmt.execute("DELETE Records WHERE Roll="+enter_id); //for deleting a record
Read this first -->Java program to connect to a database
No comments:
Post a Comment