<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: mysql code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 11 Oct 2008 04:07:47 GMT</pubDate>
    <description>DZone Snippets: mysql code</description>
    <item>
      <title>mysql importing without dropping tables</title>
      <link>http://snippets.dzone.com/posts/show/6243</link>
      <description>// Had to import a lot of .sql backups into one server.  Unfortunately they included a lot of DROP TABLE statements which constantly hosed my data. Here I have skewered sed to delete those sql statements before importing.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;br /&gt;# Create a temporary filename&lt;br /&gt;uniq="/tmp/temp_"`date "+%s"`&lt;br /&gt;&lt;br /&gt;for item in `ssh user@dbserver ls`;&lt;br /&gt;do&lt;br /&gt;     echo -n "Importing $item..."&lt;br /&gt;     scp user@dbserver\:$item $uniq;&lt;br /&gt;     gunzip &lt; $uniq | sed {/$'DROP TABLE IF EXISTS'/d} | mysql -f -u root $DB_SCHEMA_NAME&lt;br /&gt;     echo "..done"&lt;br /&gt;done&lt;br /&gt;&lt;br /&gt;# clean up&lt;br /&gt;rm -f "$uniq"&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 10 Oct 2008 07:28:16 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/6243</guid>
      <author>mobidata-group (Dallas)</author>
    </item>
    <item>
      <title>traffic meter by xorkrus :)</title>
      <link>http://snippets.dzone.com/posts/show/6223</link>
      <description>// harsh but worker&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/perl&lt;br /&gt;use DBD::mysql;&lt;br /&gt;use DBI;&lt;br /&gt;$nowdate = `date +'%Y%m%d'`;chop($nowdate);&lt;br /&gt;$host = ('localhost');&lt;br /&gt;$dbase = ('tmbx');&lt;br /&gt;$user = ('tmbx');&lt;br /&gt;$pass = ('tmbx');&lt;br /&gt;$tzinb = `cat /proc/net/dev | grep ppp0 | awk '{printf \$2}'`;&lt;br /&gt;$tzoutb = `cat /proc/net/dev | grep ppp0 | awk '{printf \$10}'`;&lt;br /&gt;$trc = DBI-&gt;trace(0);&lt;br /&gt;        my $dbh = DBI-&gt;connect("DBI:mysql:$dbase;$host", "$user", "$pass",{'RaiseError' =&gt; 1});&lt;br /&gt;        $lsn = $dbh-&gt;prepare("SELECT MAX(sn) FROM session") or die print "$DBI::errstr\n";&lt;br /&gt;        $lsn-&gt;execute();&lt;br /&gt;        my $ref = $lsn-&gt;fetchrow_hashref();&lt;br /&gt;        $mlsn = $ref-&gt;{'MAX(sn)'};&lt;br /&gt;        $lsn-&gt;finish();&lt;br /&gt;        my $oth = $dbh-&gt;prepare("SELECT * FROM session WHERE sn='$mlsn'") or die print "$DBI::errstr\n";&lt;br /&gt;        $oth-&gt;execute();&lt;br /&gt;        my $refa = $oth-&gt;fetchrow_hashref();&lt;br /&gt;        $tinb = $refa-&gt;{'inb'};&lt;br /&gt;        $toutb = $refa-&gt;{'outb'};&lt;br /&gt;        $tdate = $refa-&gt;{'date'};&lt;br /&gt;        $oth-&gt;finish();&lt;br /&gt;        $nsn = $mlsn+1;&lt;br /&gt;        $tndate = `echo $tdate | sed -e 's/-//'|sed -e 's/-//'`;chop($tndate);&lt;br /&gt;if ($tzinb &gt; $tinb &amp;&amp; $tndate &lt; $nowdate) {&lt;br /&gt;        $nzinb = $tzinb-$tinb;&lt;br /&gt;        $nzoutb = $tzoutb-$toutb;&lt;br /&gt;        my $sth = $dbh-&gt;prepare("INSERT INTO session (date, sn, inb, outb) VALUES ('$nowdate', '$nsn', '$nzinb', '$nzoutb')") or die print "$DBI::errstr\n";&lt;br /&gt;        &amp;DayRef;&lt;br /&gt;        $sth-&gt;execute();&lt;br /&gt;        }&lt;br /&gt;if ($tzinb &gt; $tinb &amp;&amp; $tndate == $nowdate) {&lt;br /&gt;        my $sth = $dbh-&gt;prepare("UPDATE session SET date='$nowdate', sn='$mlsn', inb='$tzinb', outb='$tzoutb' WHERE sn='$mlsn';") or die print "$DBI::errstr\n";&lt;br /&gt;        $sth-&gt;execute();&lt;br /&gt;        }&lt;br /&gt;if ($tzinb &lt; $tinb) {&lt;br /&gt;        my $sth = $dbh-&gt;prepare("INSERT INTO session (date, sn, inb, outb) VALUES ('$nowdate', '$nsn', '$tzinb', '$tzoutb');") or die print "$DBI::errstr\n";&lt;br /&gt;        $sth-&gt;execute();&lt;br /&gt;        }&lt;br /&gt;sub DayRef {&lt;br /&gt;        $ddate=$nowdate-1;&lt;br /&gt;        my $ath = $dbh-&gt;prepare("SELECT SUM(inb), SUM(outb) FROM session WHERE date='$ddate'") or die print "$DBI::errstr\n";&lt;br /&gt;        $ath-&gt;execute();&lt;br /&gt;        my $aref = $ath-&gt;fetchrow_hashref();&lt;br /&gt;        $mtinb = $aref-&gt;{'SUM(inb)'};&lt;br /&gt;        $mtoutb = $aref-&gt;{'SUM(outb)'};&lt;br /&gt;        $ath-&gt;finish();&lt;br /&gt;        my $ath2 = $dbh-&gt;prepare("INSERT INTO traffic (date,inb,outb) VALUES ('$ddate','$mtinb','$mtoutb')") or die print "$DBI::errstr\n";&lt;br /&gt;        $ath2-&gt;execute();&lt;br /&gt;        $ath2-&gt;finish();}&lt;br /&gt;        $dbh-&gt;disconnect();&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 07 Oct 2008 23:39:36 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/6223</guid>
      <author>xorkrus (Valentin)</author>
    </item>
    <item>
      <title>Rails Migration to convert latin1 MySQL DB to UTF8</title>
      <link>http://snippets.dzone.com/posts/show/6070</link>
      <description>&lt;code&gt;&lt;br /&gt;class ConvertDbToUtf8 &lt; ActiveRecord::Migration&lt;br /&gt;&lt;br /&gt;  def self.up&lt;br /&gt;    db_config = ActiveRecord::Base.connection.instance_values["config"]&lt;br /&gt;    db_name = db_config[:database]&lt;br /&gt;    db_user = db_config[:username]&lt;br /&gt;    db_pass = db_config[:password] || ''&lt;br /&gt;    &lt;br /&gt;    latin1_dump = 'latin1_dump.sql'&lt;br /&gt;    utf8_dump   = 'utf8_dump.sql'&lt;br /&gt;    &lt;br /&gt;&lt;br /&gt;    print "Dumping database... "&lt;br /&gt;    system "mysqldump --user=#{db_user} --password='#{db_pass}' --add-drop-table --default-character-set=latin1 --insert-ignore --skip-set-charset #{db_name} &gt; #{latin1_dump}"&lt;br /&gt;    puts "done"&lt;br /&gt;    &lt;br /&gt;    print "Converting dump to UTF8... "    &lt;br /&gt;    system "iconv -f ISO-8859-1 -t UTF-8 #{latin1_dump} | sed 's/latin1/utf8/' &gt; #{utf8_dump}"&lt;br /&gt;    puts "done"&lt;br /&gt;    &lt;br /&gt;    print "Recreating database..."&lt;br /&gt;    system "mysql --user=#{db_user} --password='#{db_pass}' --execute=\"DROP DATABASE #{db_name};\""&lt;br /&gt;    system "mysql --user=#{db_user} --password='#{db_pass}' --execute=\"CREATE DATABASE #{db_name} CHARACTER SET utf8 COLLATE utf8_unicode_ci;\""&lt;br /&gt;    puts "done"&lt;br /&gt;    &lt;br /&gt;    print "Importing UTF8 dump..."&lt;br /&gt;    system "mysql --user=#{db_user} --password='#{db_pass}' --default-character-set=utf8 #{db_name} &lt; #{utf8_dump}"&lt;br /&gt;    puts "done"&lt;br /&gt;&lt;br /&gt;    puts " *** don't forget to delete temp files #{latin1_dump} and #{utf8_dump}"&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def self.down&lt;br /&gt;    raise "cant revert sorry"&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 13 Sep 2008 03:00:38 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/6070</guid>
      <author>regabi (Remi)</author>
    </item>
    <item>
      <title>mysql search + replace</title>
      <link>http://snippets.dzone.com/posts/show/6052</link>
      <description>// Performing a search-and-replace through a table is easy with MySQL when you know how.&lt;br /&gt;// http://blog.urbanmainframe.com/2008/07/mysql-search-replace/&lt;br /&gt;&lt;br /&gt;&lt;code&gt;update table_name set table_field = replace(table_field,'replace_that','with_this');&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;So, for example, let&#8217;s say you have a table called &#8220;posts&#8221; with a data stored in a field called &#8220;content&#8221; and you want to replace all instances of the word &#8220;dog&#8221; with &#8220;cat&#8221;, then your SQL would look like this:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;update posts set content = replace(content,'dog','cat');&lt;/code&gt;</description>
      <pubDate>Tue, 09 Sep 2008 15:20:18 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/6052</guid>
      <author>wdm (wdm)</author>
    </item>
    <item>
      <title>MYSQL - column copy with string replacement</title>
      <link>http://snippets.dzone.com/posts/show/5960</link>
      <description>MySql snippet to copy a column in a table to another column, with some string manipulation.&lt;br /&gt;Create new_col before executing this segment. &lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;UPDATE table SET table.new_col=REPLACE(table.old_col,'str2replace','replace_with_str');&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 21 Aug 2008 01:46:03 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5960</guid>
      <author>srgama (sr)</author>
    </item>
    <item>
      <title>running total in PHP</title>
      <link>http://snippets.dzone.com/posts/show/5889</link>
      <description>// output running total&lt;br /&gt;// userID,posts,runningTotal|&lt;br /&gt;// 2,23434,28330|&lt;br /&gt;// 6,3443,4896|&lt;br /&gt;// 1,422,1453|&lt;br /&gt;// 3,344,1031|&lt;br /&gt;// 4,344,687|&lt;br /&gt;// 5,343,343|&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;$q = mysql_query("select * from `members` order by `posts` DESC");&lt;br /&gt;echo 'userID,posts,runningTotal|&lt;br&gt;';&lt;br /&gt;while($a = mysql_fetch_row($q)){&lt;br /&gt;echo "$a[0],$a[1],$total|&lt;br&gt;";&lt;br /&gt;$total = $total - $a[1];&lt;br /&gt;}  &lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 08 Aug 2008 11:26:51 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5889</guid>
      <author>shantanuo (shantanu oak)</author>
    </item>
    <item>
      <title>Create MySQL user</title>
      <link>http://snippets.dzone.com/posts/show/5862</link>
      <description>&lt;code&gt;grant all privileges on db_name.table_name (or .*) to 'username'@'localhost' identified by 'password';&lt;/code&gt;</description>
      <pubDate>Thu, 31 Jul 2008 16:50:34 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5862</guid>
      <author>flynets (Flynets is an italian student of computer science with passion for GNU/Linux and hacktivism.)</author>
    </item>
    <item>
      <title>Compare Engines </title>
      <link>http://snippets.dzone.com/posts/show/5806</link>
      <description>// If you have 2 servers with identical database structure, and some of the tables have different engine type, then create a federated table to connect to the original server and compare the engines type with the current table's engine.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;CREATE TABLE test.`TABLES2` (&lt;br /&gt;`TABLE_CATALOG` varchar(512) default NULL,&lt;br /&gt;`TABLE_SCHEMA` varchar(64) NOT NULL default '',&lt;br /&gt;`TABLE_NAME` varchar(64) NOT NULL default '',&lt;br /&gt;`TABLE_TYPE` varchar(64) NOT NULL default '',&lt;br /&gt;`ENGINE` varchar(64) default NULL,&lt;br /&gt;`VERSION` bigint(21) default NULL,&lt;br /&gt;`ROW_FORMAT` varchar(10) default NULL,&lt;br /&gt;`TABLE_ROWS` bigint(21) default NULL,&lt;br /&gt;`AVG_ROW_LENGTH` bigint(21) default NULL,&lt;br /&gt;`DATA_LENGTH` bigint(21) default NULL,&lt;br /&gt;`MAX_DATA_LENGTH` bigint(21) default NULL,&lt;br /&gt;`INDEX_LENGTH` bigint(21) default NULL,&lt;br /&gt;`DATA_FREE` bigint(21) default NULL,&lt;br /&gt;`AUTO_INCREMENT` bigint(21) default NULL,&lt;br /&gt;`CREATE_TIME` datetime default NULL,&lt;br /&gt;`UPDATE_TIME` datetime default NULL,&lt;br /&gt;`CHECK_TIME` datetime default NULL,&lt;br /&gt;`TABLE_COLLATION` varchar(64) default NULL,&lt;br /&gt;`CHECKSUM` bigint(21) default NULL,&lt;br /&gt;`CREATE_OPTIONS` varchar(255) default NULL,&lt;br /&gt;`TABLE_COMMENT` varchar(80) NOT NULL default ''&lt;br /&gt;)&lt;br /&gt;ENGINE=FEDERATED DEFAULT CHARSET=latin1&lt;br /&gt;CONNECTION='mysql://root@172.172.172.172/information_schema/TABLES';&lt;br /&gt;&lt;br /&gt;SELECT b.TABLE_SCHEMA as remote_database, b.TABLE_NAME as remote_tableName, b.ENGINE as remote_engine, a.ENGINE AS local_engine &lt;br /&gt;FROM test.TABLES2 AS a INNER JOIN information_schema.TABLES as b &lt;br /&gt;ON a.TABLE_SCHEMA = b.TABLE_SCHEMA AND a.TABLE_NAME = b.TABLE_NAME AND a.ENGINE != b.ENGINE;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 22 Jul 2008 05:47:46 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5806</guid>
      <author>shantanuo (shantanu oak)</author>
    </item>
    <item>
      <title>Claves Foraneas / Foreign key</title>
      <link>http://snippets.dzone.com/posts/show/5777</link>
      <description>Integridad de datos mediantes claves Foraneas, script que genera las SQL necesarios para garantizar la integridad entre tablas. Poco a poco vamos relacionando parejas de padre e hijo y podemos realizar un arbol de claves foraneas, cuando si borramos un registro del padre, borra y actualiza a los hijos en cascada, si no me explico bien decirme en los comentarios.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;?php&lt;br /&gt;require_once("cabezera/funciones.php");&lt;br /&gt;conectar_mysql();&lt;br /&gt;require_once("cabezera/scripts/constantes.php");&lt;br /&gt;?&gt;&lt;br /&gt;&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;&lt;br /&gt;&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;br /&gt;&lt;head&gt;&lt;br /&gt;&lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2" /&gt;&lt;br /&gt;&lt;title&gt;Untitled Document&lt;/title&gt;&lt;br /&gt;&lt;/head&gt;&lt;br /&gt;&lt;br /&gt;&lt;body&gt;&lt;br /&gt;&lt;?php&lt;br /&gt;$ejecutar = isset($_GET['ejecutar']) &amp;&amp; $_GET['ejecutar']=='si';&lt;br /&gt;$tabla_padre = "album";&lt;br /&gt;$tabla_hijo = "fotos";&lt;br /&gt;$campo_padre = "idAlbum";&lt;br /&gt;$campo_hijo = "idAlbum";&lt;br /&gt;&lt;br /&gt;$sinIntegridad = 0;&lt;br /&gt;&lt;br /&gt;$sql="select * from ".$tabla_hijo;&lt;br /&gt;$resultado = mysql_query($sql);&lt;br /&gt;while($fila = mysql_fetch_array($resultado))&lt;br /&gt;{&lt;br /&gt;	$sql2 = "select * from ".$tabla_padre." where ".$campo_padre." = '".$fila[$campo_hijo]."'";&lt;br /&gt;	//echo $sql2."&lt;br/&gt;";&lt;br /&gt;	$resultado2 = mysql_query($sql2);&lt;br /&gt;	if(mysql_num_rows($resultado2) &lt;= 0)&lt;br /&gt;	{&lt;br /&gt;		$sql3 = "DELETE FROM `".$tabla_hijo."` WHERE `".$campo_hijo."` = '".$fila[$campo_hijo]."' LIMIT 1;";&lt;br /&gt;		if($ejecutar)&lt;br /&gt;		{&lt;br /&gt;			if(mysql_query($sql3)) echo "OK query : ".$sql3."&lt;br /&gt;";&lt;br /&gt;			else echo "Error en query : ".$sql3."&lt;br /&gt;";&lt;br /&gt;		}&lt;br /&gt;		else&lt;br /&gt;		{&lt;br /&gt;			echo $sql3."&lt;br/&gt;";&lt;br /&gt;		}&lt;br /&gt;		$sinIntegridad++;&lt;br /&gt;	}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;$sql1="ALTER TABLE `".$tabla_padre."` ADD INDEX ( `".$campo_padre."` ) ";&lt;br /&gt;$sql2="ALTER TABLE `".$tabla_hijo."` ADD INDEX ( `".$campo_hijo."` ) ";&lt;br /&gt;$sql3="ALTER TABLE ".$tabla_hijo." ADD FOREIGN KEY(".$campo_hijo.") REFERENCES ".$tabla_padre." (".$campo_padre.") ON DELETE CASCADE ON UPDATE CASCADE";&lt;br /&gt;if($ejecutar)&lt;br /&gt;{&lt;br /&gt;	if(mysql_query($sql1)) echo "OK query : ".$sql1."&lt;br /&gt;";&lt;br /&gt;	else echo "Error en query : ".$sql1."&lt;br /&gt;";&lt;br /&gt;	&lt;br /&gt;	if(mysql_query($sql2)) echo "OK query : ".$sql2."&lt;br /&gt;";&lt;br /&gt;	else echo "Error en query : ".$sql2."&lt;br /&gt;";&lt;br /&gt;	&lt;br /&gt;	if(mysql_query($sql3)) echo "OK query : ".$sql3."&lt;br /&gt;";&lt;br /&gt;	else echo "Error en query : ".$sql3."&lt;br /&gt;";&lt;br /&gt;}&lt;br /&gt;else&lt;br /&gt;{&lt;br /&gt;	echo $sql1."&lt;br/&gt;";&lt;br /&gt;	echo $sql2."&lt;br/&gt;";&lt;br /&gt;	echo $sql3."&lt;br/&gt;";&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;echo "&lt;br/&gt;".$sinIntegridad." filas sin integridad.&lt;br/&gt;";&lt;br /&gt;?&gt;&lt;br /&gt;&lt;form id="form1" name="form1" method="get" action=""&gt;&lt;br /&gt;  &lt;label&gt;&lt;br /&gt;  &lt;input name="ejecutar" type="hidden" id="ejecutar" value="si" /&gt;&lt;br /&gt;  &lt;input name="Button" type="button" onclick="location.href=location.href" value="Recargar sin ejecutar nada" /&gt;&lt;br /&gt;  &lt;input type="submit" name="button" id="button" value="Ejecutar SQL!" /&gt;&lt;br /&gt;  &lt;/label&gt;&lt;br /&gt;&lt;/form&gt;&lt;br /&gt;&lt;?php&lt;br /&gt;/*&lt;br /&gt;ALTER TABLE fotos_nueva_version ADD FOREIGN KEY(idUsuario) REFERENCES usuarios_portalcocinas (idUsuario) ON DELETE CASCADE ON UPDATE CASCADE&lt;br /&gt;&lt;br /&gt;ALTER TABLE relacion_usuario_localidad ADD FOREIGN KEY(idUsuario) REFERENCES usuarios_portalcocinas (idUsuario) ON DELETE CASCADE ON UPDATE CASCADE&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;ALTER TABLE relacion_usuario_actividad ADD FOREIGN KEY(idUsuario) REFERENCES usuarios_portalcocinas (idUsuario) ON DELETE CASCADE ON UPDATE CASCADE&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;ALTER TABLE fotos_nueva_version DROP FOREIGN KEY idUsuario_FK;&lt;br /&gt;&lt;br /&gt;SHOW CREATE TABLE fotos_nueva_version;&lt;br /&gt;*/&lt;br /&gt;?&gt;&lt;br /&gt;&lt;/body&gt;&lt;br /&gt;&lt;/html&gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 16 Jul 2008 12:18:14 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5777</guid>
      <author>Ricardo (Ricardo m. Garc&#237;a)</author>
    </item>
    <item>
      <title>Query MySQL accent insensitive in latin1_general_ci</title>
      <link>http://snippets.dzone.com/posts/show/5677</link>
      <description>Query MySQL accent insensitive in latin1_general_ci&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;SELECT * FROM `table`WHERE `text` LIKE CONVERT(_utf8 '%cinema%' USING utf8) COLLATE utf8_general_ci ;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.ab-d.fr/"&gt;Source: &lt;/a&gt;&lt;a href="http://www.ab-d.fr/date/2008-06-21/"&gt;Query MySQL accent insensitive in latin1_general_ci&lt;/a&gt;</description>
      <pubDate>Sat, 21 Jun 2008 10:34:59 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5677</guid>
      <author>ki4ngel (Benoit Asselin)</author>
    </item>
  </channel>
</rss>
