ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%z' at line 1
root@7c6316b19d80:/# mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 140 Server version: 5.6.51 MySQL Community Server (GPL)mysql> mysql> select * from test_user where address like 'Hang%'; +----+--------+-------------+----------+ | id | name | mobile | address | +----+--------+-------------+----------+ | 3 | python | 18856565858 | Hangzhou | | 4 | java | 17756565858 | Hangzhou | | 5 | php | 15556565858 | Hangzhou | | 6 | c# | 17748484142 | Hangzhou | +----+--------+-------------+----------+ 4 rows in set (0.00 sec) mysql>
查询地址以u结尾的人员信息
mysql> select * from test_user where address like '%u'; +----+--------+-------------+----------+ | id | name | mobile | address | +----+--------+-------------+----------+ | 3 | python | 18856565858 | Hangzhou | | 4 | java | 17756565858 | Hangzhou | | 5 | php | 15556565858 | Hangzhou | | 6 | c# | 17748484142 | Hangzhou | +----+--------+-------------+----------+ 4 rows in set (0.00 sec) mysql>
示例2:使用python脚本执行含LIKE的sql语句
查询地址包含z字符的人员信息
import pymysql# 连接数据库 connection = pymysql.connect(host="localhost", user="root", password="123456",database="testing", port=3306, charset='utf8',cursorclass=pymysql.cursors.DictCursor)try:with connection:with connection.cursor() as cursor:sql = """SELECT*FROMtest_userWHEREaddress LIKE '%z%';"""cursor.execute(sql)result = cursor.fetchall()for i in result:print(i)except pymysql.err.MySQLError as _error:raise _error
try:with connection:with connection.cursor() as cursor:sql = """SELECT*FROMtest_userWHEREaddress NOT LIKE '%z%';"""cursor.execute(sql)result = cursor.fetchall()for i in result:print(i)except pymysql.err.MySQLError as _error:raise _error