Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Updating a database

Status
Not open for further replies.

johno77

Technical User
Nov 1, 2003
40
GB
Hello

I have created the following code to update a paticular mysql record. Could any one inform me of how if the record is not present to add it to the database.

Thanks - heres the relevant code


try {
String query1 = "UPDATE system SET cox='"+first+"', def='"+second+"' WHERE name_d='"+name+"'";
System.out.println(query1);
Statement state1 = connect.createStatement();
ResultSet resultset1=state1.executeQuery(query1);
JOptionPane.showMessageDialog(null,"Database updated: ");

}
catch (Exception exp)
{
JOptionPane.showMessageDialog(null,"Problem with SQL query" + input );
}
 
Your SQL will be something like
Code:
INSERT INTO system VALUES ('one', 'two', 'three');

To determine whether or not you need to do an update or insert, you could execute some SQL such as

Code:
SELECT COUNT(*) FROM system WHERE name_d = 'qqq';

If it is 0, then INSERT, if its not then UPDATE.
 
I think that you can take a boolean response from the statement and not a resultSet.

boolean res = state1.execute(query1);
if(!res){
String query2 = "INSERT INTO ......";
state1.execute(query2);
}

so you can control the result of the first query. If it's fail you execute the second (insert query)

Grentis
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top