tags:

views:

48

answers:

4

I am trying to take the output of a JAVA program consisting of an array of 12 for a bunch of different users and place them into a table. Is there anyway to do this in bulk, without having to do it one at a time?

+2  A: 

I've done it like so:

INSERT INTO my_users (name, passwd, somefield)
VALUES 
 ('joe', 'pass', 'abc'),
 ('jeff', 'pass1', 'abcd'),
 ('jake', 'pass2', 'abcde')
Mondain
I know it's not the point of your example, but...plaintext passwords in the database?!?
Piskvor
Those only look plain-text, that's how good my encryption is :)
Mondain
@Mondain: ah, you're actually storing passwords in `somefield` and just keep `passwd` around to fool the hackers, I see. Very cunning, indeed!
Quassnoi
A: 

INSERT allows you to insert multiple values at once:

INSERT
INTO
    table
    (column_a, column_b, column_c)
VALUES
    (1, 2, 3),
    (4, 5, 6),
    (7, 8, 9)
;

This is standard SQL, and should work on most databases. (There are a few exceptions I've come across: outdated DBs and MSSQL, but you're on MySQL, which supports this.)

Thanatos
+1  A: 

Could always have the data written to a file, and use the LOAD DATA INFILE statement to bulk read them into the database. But depending on the scale, it might not be worth it worrying about speed here.

zigdon
+1  A: 

Use batch insert. Adapting from http://www.roseindia.net/jdbc/jdbc-mysql/PreparedStatementBatchUpdate.shtml :

  Connection conn;
  User[] users;

  PreparedStatement prest = con.prepareStatement("INSERT INTO users VALUES(?,?)");

  conn.setAutoCommit(false);
  for(user : users) {
      prest.setString(1, User.getUserName());
      prest.setInt(2, User.getAge());
  }
  prest.addBatch();

  int count[] = prest.executeBatch();

  conn.setAutoCommit(true);
  prest.close();

In the real world, you will want to sprinkle this with a bunch of try..finally blocks, but I will assume you know or can find elsewhere how to do that.

ykaganovich
Rose India as a citation? Please.
duffymo
needed to look up the syntax, and haven't done this in a while... just knew what to look for :)
ykaganovich