From CSV to MySQL Database Using Perl -


I tried to upload some data from CSV into a MySQL database - but this is not working

Below is my code

  #! / Usr / bin / perl -w Usage DBI; Strict use; Use of Text :: CSV; Use warnings; My $ driver = "mysql"; My $ database = "test"; My $ host = "localhost" my $ databases = "3306"; My $ userid = "root"; My $ password = "password"; My $ csv = "c: /Perl/scripts/table.csv"; My $ dsn = "dbi: mysql: dbname = $ databasename; host = $ dbhost; ports = $ dbport;"; Open (CSV, "$ CSV") or dead "CSV file can not be opened: $!"; My $ dbh = dbi- & gt; Connect ($ dsn, $ userid, $ password, {RaiseError => 1}) or die "Could not connect to database! $ DBI :: errstr"; {Local $ / = Anf; $ Dbh- & gt; ("INSERT INTO STUDENT (stud_id, stud_name, dept_id, stud_mark, stud_address) value (?,?,?,?,?)", Undefined, & lt; csv & gt;); } $ Dbh- & gt; Disconnected; Closed CSV; Here are some issues I will list those who will give you an error message before.  
  • There is no module TEXT :: CSV is called a though.
  • You are using 5 placeholders in your query, but you can use Diamond operator & lt; CSV & gt; The first line of the CSV file is passing through . This will give an error message.

Then there are problems in your logic. I am passing the whole file as DB (first argument). that does not make sense. Partition To input or text: Need to use CSV and read the file line from the line.

In addition to this, nowadays use open with three arguments and filehandsal lexical to use it.

I have written all this as an example with CSV handling I created. If your file is more complex, then use it on text: CSV and use it.

  Use DBI; Strict use; Use warnings; My $ csv = "c: /Perl/scripts/table.csv"; # Removed settings here ... my $ dbh = dbi- & gt; Connect ($ DSN, $ user ID, $ password, {RaiseError => 1)) or die "Could not connect to database! $ DBI :: errstr"; Open (my $ FH, '& lt;', $ csv) or die "CSV file can not be opened: $!"; # Ready statement to my $ sth = $ dbh- & gt; Prepare to reuse in the loop (qq {enter student (stud_id, stud_name, dept_id, stud_mark, stud_address) value (?,?,?,?,?)}); Read the file line by # line (my $ line = & lt; $ fh & gt;) {chomp $ line; #newline $ sth- & gt; Execute (partition /; /, $ line); # Separator is a semicolon) close to $ FH; #db handle will disconnect at the end of the program in the manner vested  

As you can see, I have decided to come in and reuse it. It saves a lot of time in the loop, because DB will remember the statement.


Comments