mysql 一次更新(update)多條記錄的思路_Mysql

來源:互聯網
上載者:User

工作中遇到一個問題:要更新一個資料表。

這個表是我自己建立的,有7個欄位,id、name、package等等

建立的時候,因為我把name、package的資訊分別存在兩個文字檔中,

所以我就用Insert方法,一次性將所有的name插入資料庫中。

name全部匯入資料庫中了,但是我的package沒有匯入,這時我仍然想用insert的方法插入,但是不行。

這時候應該利用update的方法。一次更新多條資訊的思路如下:

UPDATE table_name SET field_name = CASE other_field WHEN 1 THEN 'value' WHEN 2 THEN 'value' WHEN 3 THEN 'value' END WHERE id IN (1,2,3)測試代碼如下:<?php /* *function: insert app's apk ,logo_url, document_title,app_desc,package_name * into talbe atable use database db . */ //connect database catx. $server='localhost'; $user='root'; $passwd='root'; $port='3306'; $dbname='catx'; $link=mysql_connect($server,$user,$passwd); if (!$link) { die('Could not connect: ' . mysql_error()); } else echo "Connected successfully\n"; mysql_select_db("db",$link); //set init variable and start time $st=microtime_float(); $table="pydot_g"; $path = "txt"; $fname_package_name = "package_name.txt"; // $handle= @fopen($path."/".$fname_package_name, "r"); $i=1; $sql = "UPDATE pydot_g SET package_name = CASE id "; $ids=""; while(($buf[$i]=fgets($handle,512))!==false){ $sql .= sprintf("WHEN %d THEN '%s' ", $i, $buf[$i]); // 拼接SQL語句 $ids .= sprintf("%d,",$i); $i++; } //$ids=implode(',',$ids); $ids.=$i; $sql .= "END WHERE id IN ($ids)"; echo $sql; mysql_query($sql); fclose($handle); mysql_close($link); //echo the results and total time used $et=microtime_float(); $t=$et-$st; echo "\r\ninsert into talbe ",$table," ",$i,"times;\r\n"; echo "Total time $t seconds.\r\n"; //function calculate time ,return a float number function microtime_float(){ list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } ?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.