Articles

Função MySQL REPLACE()

Última actualização a 26 de Fevereiro de 2020 08:08:23 (UTC/GMT +8 horas)

REPLACE() function

MySQL REPLACE() substitui todas as ocorrências de um substrato dentro de uma string.

Syntax:

REPLACE(str, find_string, replace_with)

Argumentos

replace_with

Nome Descrição
str Uma cadeia de caracteres.
find_string Uma cadeia de caracteres que está presente uma ou mais vezes dentro da cadeia de caracteres.
Uma cadeia de caracteres que substituirá cada vez que encontrar_string dentro da cadeia de caracteres.

Diagrama de sintaxe:

MySQL REPLACE() Function - Syntax Diagrambr>

MySQL Version: 5.6

MySQL: Replace Presentation - w3resource
p>Video Presentation:p>Seu navegador não suporta vídeo HTML5.

Exemplo da função MySQL REPLACE()

A seguinte declaração MySQL substitui cada vez que encontra ‘ur’ dentro do ‘w3resource’ por ‘r’.

Código :

SELECT REPLACE('w3resource','ur','r');

Sample Output:

mysql> SELECT REPLACE('w3resource','ur','r');+--------------------------------+| REPLACE('w3resource','ur','r') |+--------------------------------+| w3resorce | +--------------------------------+1 row in set (0.02 sec)

Apresentação pictórica

MySQL REPLACE pictorial presentationMySQL REPLACE apresentação pictórica

Exemplo da função MySQL REPLACE() com a cláusula

A seguinte declaração MySQL substitui todas as ocorrências de ‘K’ por ‘SA’ dentro da coluna país da editora da tabela para essas linhas, em que o valor da coluna do país é o Reino Unido.

Código:

SELECT pub_city,country,REPLACE(country,'K','SA') FROM publisher WHERE country='UK';

Tabela de amostras: editora

p>P>Sample Output:

mysql> SELECT pub_city,country, -> REPLACE(country,'K','SA') -> FROM publisher -> WHERE country='UK';+-----------+---------+---------------------------+| pub_city | country | REPLACE(country,'K','SA') |+-----------+---------+---------------------------+| London | UK | USA | | Cambridge | UK | USA | +-----------+---------+---------------------------+2 rows in set (0.05 sec)

PHP script

<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>example-replace-function - php mysql examples | w3resource</title><meta name="description" content="example-replace-function - php mysql examples | w3resource"><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"></head><body><div class="container"><div class="row"><div class="col-md-12"><h2>A list of Publishers those who belong to USA. Right column shows the name of the publisher enclosed with single quotes:</h2><table class='table table-bordered'><tr><th>Publishers city</th><th>Publishers country</th><th>Value of Publishers country where string 'k' is replaced with 'sa':</th></tr><?php$hostname="your_hostname";$username="your_username";$password="your_password";$db = "your_dbname";$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);foreach($dbh->query('SELECT pub_city,country,REPLACE(country,"K","SA") as output FROM publisherWHERE country="UK"') as $row) {echo "<tr>";echo "<td>" . $row . "</td>"; echo "<td>" . $row . "</td>";echo "<td>" . $row . "</td>";echo "</tr>"; }?></tbody></table></div></div></div></body></html>

Ver o exemplo no browser

JSP script

<%@page contentType="text/html" pageEncoding="UTF-8"%><%@ page import="java.sql.*" %><%@ page import="java.io.*" %><!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>example-replace-function</title></head><body><%try {Class.forName("com.mysql.jdbc.Driver").newInstance();String Host = "jdbc:mysql://localhost:3306/w3resour_bookinfo";Connection connection = null;Statement statement = null;ResultSet rs = null;connection = DriverManager.getConnection(Host, "root", "datasoft123");statement = connection.createStatement();String Data ="SELECT pub_city,country,REPLACE(country,'K','SA') as output FROM publisher WHERE country='UK'";rs = statement.executeQuery(Data);%><TABLE border="1"><tr width="10" bgcolor="#9979"><td>Publishers city</td><td>Publishers country</td><td>Value of Publishers country where string 'k' is replaced with 'sa'</td></tr><%while (rs.next()) {%><TR><TD><%=rs.getString("pub_city")%></TD><TD><%=rs.getString("country")%></TD><TD><%=rs.getString("output")%></TD></TR><% } %></table><%rs.close();statement.close();connection.close();} catch (Exception ex) {out.println("Cant connect to database.");}%></body></html>

MySQL: Encontrar e Substituir Dados

Temos uma tabela chamada teste com os seguintes registos :

mysql> SELECT * FROM test;+-----------+| test_char |+-----------+| Abcd || Wxyz || Scott || Robin |+-----------+4 rows in set (0.00 sec)

Para encontrar e substituir ‘Scott’ por ‘Sidhu’ pode usar a seguinte declaração MySQL :

mysql> UPDATE test set test_char = replace(test_char, 'Scott', 'Sidhu');Query OK, 1 row affected (0.04 sec)Rows matched: 4 Changed: 1 Warnings: 0mysql> SELECT * FROM test;+-----------+| test_char |+-----------+| Abcd || Wxyz || Sidhu || Robin |+-----------+4 rows in set (0.00 sec)

Todas as funções de String

MySQL String Functions, slide presentation

Previous: REPEAT
Next: REVERSE

Deixe uma resposta

O seu endereço de email não será publicado. Campos obrigatórios marcados com *