Archive for the ‘Mysql’ Category

Como atualizar parte de uma string em uma tabela.

Monday, February 18th, 2008

Atualizar dados em lote nem sempre é simples, principalmente quando você precisa atualizar parte de um campo, por exemplo um campo de URL, voce precisa trocar http://mysql.com para http://dev.mysql.com, preservando o restante da url. veja como:

mysql> UPDATE tabela SET tbl_url=REPLACE(tlb_url, ‘http://mysql.com’, ‘http://dev.mysql.com);

O restante das urls continuarão intactos. ;-)
Boa sorte.

Selecionar registros diferentes para chaves iguais

Saturday, February 16th, 2008

Imagine que você tem uma tabela de times (id,nome) e uma tabela de jogos (id,time1_id,time2_id,data) e vc precisa selecionar os jogos no formato:

20/10/2007 - FLUMINENSE x FLAMENGO

Simples, basta trazer 2 vezes a tabela de times e relacionar cada uma com seu id na tabela de jogos:

mysql->

SELECT
data as DATA,
CONCAT_WS(’ x ‘,d.nome, e.nome) AS JOGO
FROM
jogos, time AS d, time as e
WHERE
c.time1_id=d.id and
c.time2_id =e.id 

Listar todas as tabelas e suas chaves primárias

Friday, February 15th, 2008

mysql->use INFORMATION_SCHEMA;

mysql-> select CONCAT(t.table_name,”.”,t.table_schema) as tbl,
c.column_name,c.constraint_name
from TABLES AS t LEFT JOIN KEY_COLUMN_USAGE AS c
ON (t.TABLE_NAME=c.TABLE_NAME
AND c.CONSTRAINT_SCHEMA=t.TABLE_SCHEMA
AND constraint_name=’PRIMARY’)
WHERE t.table_schema!=”information_schema”
order by constraint_name;

Novo engine mysql: Maria

Friday, February 15th, 2008

Esses dias nos Imasters li uma rtigo sobre a chegada do Maria, um novo engine mysql 5., que basicamente é um MyIsam com crash safe.

O Crash safe, é feito via full log, entao a maria é um myIsam que faz recover apartir de todo o log, ou seja, de todas as funções INSERT,DELETE, TRUNCATE, CREATE, DROP, RENANE , e todas as demais.

Criando uma tabela Maria:

mysql> CREATE TABLE maria_table (id int) ENGINE=Maria;

Transformando uma tabela MyIsam em Maria:

mysql> ALTER TABLE myisam_table ENGINE=Maria;

Arquivos que compõe o Maria:

  • table.frm — Arquivo que contem a definicao da tabela.
  • table.MAD — Arquivo de dados do maria.
  • table.MAI — Arquivo de Indice.

E mais 2 arquivos adivionais

  • maria_log.???????? — O Arquivo de log onde ???????? é um numero sequencial utilizado para o recover.
  • maria_log_control — Controla e armazena o status do log do Maria.

Vale a pena testar.

Retornar informações das SPs

Tuesday, January 22nd, 2008

Boa dica, relacionar os parametros das SP’s

mysql> SELECT * FROM INFORMATION_SCHEMA.ROUTINES ;

Com essa tabela vc pode manipular procedures em lote ;-)

Definir o auto_increment da tabela

Wednesday, January 9th, 2008

Derrepente, precisamos que uma tabela inicie com um valor definido, isso pode acontecer, devido à alguma referencia com um sistema de terceiros, numa replicação ou onde a Chave primária precisa iniciar com o proximo registro da tabela mais antiga no caso de você dividir os dados em varias tabelas.

O processo é simples:

mysql -> ALTER TABLE TB_TABELA AUTO_INCREMENT = 1000;

onde 1000 será o próximo ID.

Mysql WorkBench

Monday, January 7th, 2008

Foi criado um blog do time de desenvolvimento do Mysql WorkBench, que é a ferramenta case para bases mysql.

Pra quem conhece as versões alpha, nessa nova versão fica muito claro, que estão levando a sério a ferramenta, o mysql workbench tem 2 versões, OSS e SE, a primeira é a versão para e mantida pela comunidade , a segunda uma versão comercial, nesse link você pode ver a tabela de comparação das versões.

Fiquei surpreso ao ver que o lider do time de desenvolvimento é Michael G. Zinner  Desenvolvedor do saudoso DBDesigner4 que teve seu desenvolvimento interrompido em 2004.

Outra surpresa foi saber que estão previstas versões nativas para Windows, Linux e OS X.

Feliz 2008, passei um bom tempo sem postar e responder os comentários, estava sem pc em casa, muito trabalho pra todos nós nesse ano que inicia.

MySQL Stored Procedures Auto Generator

Thursday, November 8th, 2007

Cumpre o que o nome diz o script  desenvolvido por Anas Al-Far
Gera Stored Procedures de Inclusão exclusão e listagem de todas as tabelas do banco.

Com uma mãozinha ali pode se tornar um ótimo script.

Adminiature - um phpmyadmin em ajax

Thursday, November 8th, 2007

É isso mesmo o Administure é um phpmyadmin em ajax, é claro, falta muito pra isso, nao tem todas as funcionalidades do phpmyadmin, mas a versatilidade e usabilidade, são 10.

Melhor que ficar esperando os reloads nos frames do phpmyadmin

Ajuda para testar sql injection

Thursday, November 8th, 2007

A hackbar é uma extensão para o firefox com funcionalidades que ajudam a fazer um sqlinjection e é claro prevenir.

segundo a proipria:

Simple security audit / Penetration test tool.

# New features
- Show / Hide hotkey [F9]
- Tab sensitive
- Auto load, split and focus when pressing hotkey on a new URL.
- Localized ( English and dutch for now )
- Textarea width set to 100% (removed dragbar)
- Complete code revision (OO based instead of functions)

# In general
This toolbar will help you in testing sql injections, XSS holes and site security. It is NOT a tool for executing standard exploits and it will NOT learn you how to hack a site. Its main purpose is to help a developer do security audits on his code. If you know what your doing, this toolbar will help you do it faster. If you want to learn to find security holes, you can also use this toolbar, but you will probably also need a book, and a lot of google :)
# The advantages are:
- Even the most complicated urls will be readable
- The focus will stay on the textarea, so after executing the url (ctrl+enter) you can just go on typing / testing
- The url in textarea is not affected by redirects.
- I tend to use it as a notepad :) - Usefull tools like on the fly uu/url decoding etc.
- All functions work on the currently selected text.

# Load url ( alt a )
This loads the url of the current page into the textarea.

# Split url ( alt s )
When this button is clicked, the url/text in the textarea will be split into multiple lines using the ? and & character

# Execute ( alt x, ctrl enter )
This will execute the current url in the textarea, i mostly use ctrl+enter

# INT -1 ( alt - )
First select a number in the textarea and press this button, the number will be lowered by 1 and the url will be loaded.

# INT +1 ( alt + )
Again first select a number in the textarea and press this button, 1 will be added to the number and the url will be loaded.

# MD5 Hash ( alt m )
this is a standard hashing method, often used as an encryption method for passwords. It will MD5 hash the currently selected string.

# MySQL CHAR() ( alt y )
If quotes are escaped but you did find an SQL injection thats exploitable, you can use this button to convert lets say:
load_file(’/etc/passwd’) –> load_file(CHAR(47, 101, 116, 99, 47, 112, 97, 115, 115, 119, 100))
Thus omiting the use of quotes to load a file.
You can also use this on
WHERE foo LIKE (’%bar%’) –> WHERE foo LIKE (CHAR(37, 98, 97, 114, 37))

# MsSQL CHAR() ( alt q )
Same story as MySQL CHAR(), MsSQL has a slightly different CHAR syntax
–> WHERE foo LIKE ( CHAR(37) + CHAR(98) + CHAR(97) + CHAR(114) + CHAR(37))

# Base64 encode / decode
Base64 encoding ( UU ) is often used to store data (like a return url etc.) This will help you to read those values.

# URLencode / decode
This will encode or decode the currently selected characters to url safe characters. I mostly use it to end a query with # (%23) when in a pseudo path where i cant use /* or –

Use com cuidado ;-)