开发者

Populate MySQL table from Text file

This should be an eas开发者_C百科y one. I need to populate a table from a text file. Basically, I'd like to do this in a linux shell script. Thanks!!

Example:

  • MySQL Table

Item color shape size

  • Textfile

car blue round small

carrot red square big

apple green round medium


You could run a query like this:

LOAD DATA INFILE 'data.txt' INTO TABLE yourTable
 FIELDS TERMINATED BY ' '
 LINES TERMINATED BY '\n'

And then all you need is to write a tiny shell script, executing the query.

Edit:

A complete script could look something like this:

#!/bin/bash
mysql databaseName<<EOFMYSQL
 LOAD DATA INFILE 'data.txt' INTO TABLE yourTable
  FIELDS TERMINATED BY ' '
  LINES TERMINATED BY '\n';
EOFMYSQL

The script could be executed like this:

chmod +x script.sh
./script.sh

You probably run into user issues, since the shell does not handle mysql directly. Try looking into how you can execute mysql without logging in. This should be part of just about any mysql backup script :-)


I suggest looking at the LOAD DATA INFILE documentation, that should let you import data from that format without even writing a script.


Look at the LOAD DATA INFILE syntax. Echoing a simle query to the mysql client binary should do it.


LOAD DATA INFILE is the way used to do that. Consider csv format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜