Home > Database > Mysql Tutorial > mysql 一次更新(update)多条记录

mysql 一次更新(update)多条记录

WBOY
Release: 2016-06-07 15:01:37
Original
1449 people have browsed it

工作中遇到一个问题:要更新一个数据表。 这个表是我自己创建的,有7个字段,id、name、package等等 创建的时候,因为我把name、package的信息分别存在两个文本文件中, 所以我就用Insert方法,一次性将所有的name插入数据库中。 name全部导入数据库中了,但

工作中遇到一个问题:要更新一个数据表。

这个表是我自己创建的,有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)
Copy after login

测试代码如下:

<?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);
	}
?>	
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template