Link to home
Start Free TrialLog in
Avatar of EmailSurfer
EmailSurfer

asked on

Question about sql in java?

Hello,

Could anyone offer some advise, about adding records to mysql using java.

I managed all the connection, and understand some sql. The database has two tables:

table author:
authid
lastname
firstname

table isbn:
authid
isbn

When adding values to these tables, since they are linked by the authid field. Could I use one insert statement to add values to both tables.

Or would I need to use two insert statements, one for each table?

Thanks
SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well,

You need to have two inserts.

Best Regards
Dave
Avatar of EmailSurfer
EmailSurfer

ASKER

Something like this: the values are not added for the example.

Statement statement = connection.createStatement();
String query = "INSERT INTO author(authid, lastname, firstname)VALUES
statement.executeUpdate(query);

query = "INSERT INTO isbn(authid, isbn)VALUES
statement.executeUpdate(query);
Something like this: the values are not added for the example.

?

Statement statement = connection.createStatement();
String query = "INSERT INTO author(authid, lastname, firstname)VALUES
statement.executeUpdate(query);

query = "INSERT INTO isbn(authid, isbn)VALUES
statement.executeUpdate(query);
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yes, this looks like you have the right idea.

Statement statement = connection.createStatement();
String query = "INSERT INTO author(authid, lastname, firstname)VALUES
statement.executeUpdate(query);

query = "INSERT INTO isbn(authid, isbn)VALUES
statement.executeUpdate(query);
prepared statement would be better (probably), as it gets round people entering ' into strings...

int id = 1 ;
String lastname = "Yates" ;
String firstname = "Tim" ;
PreparedStatement s = connection.prepareStatement( "INSERT INTO author( authid, lastname, firstname ) VALUES ( ?, ?, ? )" ) ;
s.setInt( 1, id ) ;
s.setString( 2, lastname ) ;
s.setString( 3, firstname ) ;
s.executeUpdate() ;