Python MySQL 更新表
任何数据库上的UPDATE操作都会更新一条或多条记录,这些记录在数据库中已经存在。你可以使用UPDATE语句更新MySQL中现有记录的值。要更新特定的记录,你需要同时使用WHERE子句。
语法
以下是MySQL中UPDATE语句的语法-
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
你可以用AND或OR运算符来组合N个条件。
例子
假设我们在MySQL中创建了一个名为EMPLAYES的表,其名称为
mysql> CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT
);
Query OK, 0 rows affected (0.36 sec)
如果我们使用INSERT语句在其中插入4条记录,如:
mysql> INSERT INTO EMPLOYEE VALUES
('Krishna', 'Sharma', 19, 'M', 2000),
('Raj', 'Kandukuri', 20, 'M', 7000),
('Ramya', 'Ramapriya', 25, 'F', 5000),
('Mac', 'Mohan', 26, 'M', 2000);
Following MySQL statement increases the age of all male employees by one year −
mysql> UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
If you retrieve the contents of the table, you can see the updated values as −
mysql> select * from EMPLOYEE;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |
+------------+-----------+------+------+--------+
| Krishna | Sharma | 20 | M | 2000 |
| Raj | Kandukuri | 21 | M | 7000 |
| Ramya | Ramapriya | 25 | F | 5000 |
| Mac | Mohan | 27 | M | 2000 |
+------------+-----------+------+------+--------+
4 rows in set (0.00 sec)
用Python更新表的内容
使用python更新MySQL表中的记录-
- 输入 mysql. connector包。
-
使用 mysql.connector.connect() 方法创建一个连接对象,将用户名、密码、主机(可选的默认:localhost)和数据库(可选的)作为参数传给它。
-
通过在上面创建的连接对象上调用 cursor() 方法,创建一个游标对象。
-
然后,将UPDATE语句作为参数传递给 execute() 方法,执行该语句。
例子
下面的例子中,所有男性的年龄都增加了一岁。
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Preparing the query to update the records
sql = '''UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M' '''
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
#Retrieving data
sql = '''SELECT * from EMPLOYEE'''
#Executing the query
cursor.execute(sql)
#Displaying the result
print(cursor.fetchall())
#Closing the connection
conn.close()
输出
[('Krishna', 'Sharma', 22, 'M', 2000.0),
('Raj', 'Kandukuri', 23, 'M', 7000.0),
('Ramya', 'Ramapriya', 26, 'F', 5000.0)
]