python 对mysql 进行数据插入 的语句
时间: 2023-12-10 13:41:21 浏览: 28
可以使用 Python 中的 MySQLdb 或者 PyMySQL 库来连接 MySQL 数据库,并进行数据插入操作。以下是一个使用 PyMySQL 插入数据的例子:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='test', port=3306, charset='utf8mb4')
cursor = db.cursor()
# 插入数据
sql = "INSERT INTO students(name, age, gender) VALUES (%s, %s, %s)"
values = ('Tom', 18, 'male')
cursor.execute(sql, values)
db.commit()
# 关闭连接
cursor.close()
db.close()
```
其中,`host`、`user`、`password`、`database`、`port` 和 `charset` 分别指定了数据库的主机名、用户名、密码、数据库名、端口和字符集。`cursor.execute()` 方法用于执行 SQL 语句,其中 `%s` 是占位符,可以通过元组 `values` 来填充。最后使用 `db.commit()` 提交事务,并关闭连接。
相关问题
python从MySQL插入数据
在Python中使用MySQL数据库插入数据,可以使用MySQL官方提供的Python驱动程序MySQL Connector/Python或第三方库PyMySQL。
以下是使用MySQL Connector/Python的示例代码:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# 创建游标对象
mycursor = mydb.cursor()
# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# 提交更改
mydb.commit()
# 输出插入的数据行的ID
print("1 行数据插入成功,ID:", mycursor.lastrowid)
```
以下是使用PyMySQL的示例代码:
```python
import pymysql
# 连接数据库
mydb = pymysql.connect(
host="localhost",
user="username",
password="password",
database="database_name"
)
# 创建游标对象
mycursor = mydb.cursor()
# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
# 提交更改
mydb.commit()
# 输出插入的数据行的ID
print("1 行数据插入成功,ID:", mycursor.lastrowid)
```
以上代码中,我们连接到MySQL数据库,创建游标对象,然后使用 `mycursor.execute()` 方法执行SQL语句插入数据,并使用 `mydb.commit()` 方法提交更改。最后,使用 `mycursor.lastrowid` 属性获取插入的数据行的ID。
python操作mysql插入数据
下面是一个Python操作MySQL插入数据的例子:
```python
import mysql.connector
# 连接MySQL数据库
cnx = mysql.connector.connect(user='username', password='password',
host='localhost',
database='mydatabase')
# 创建游标对象
cursor = cnx.cursor()
# 插入数据
add_data = ("INSERT INTO mytable "
"(id, name, age) "
"VALUES (%s, %s, %s)")
data = (1, 'Tom', 25)
cursor.execute(add_data, data)
# 提交更改
cnx.commit()
# 关闭游标和连接
cursor.close()
cnx.close()
```
在这个例子中,我们使用`mysql.connector`模块来连接MySQL数据库。然后,我们创建一个游标对象,使用`INSERT INTO`语句插入一条数据到`mytable`表中。最后,我们提交更改并关闭游标和连接。