python 连接mysql数据库,执行SQL语句得到查询的数据
时间: 2024-03-13 13:44:24 浏览: 41
要连接 MySQL 数据库,你可以使用 Python 的 MySQL Connector 模块。以下是一个简单的连接数据库并执行查询的示例代码:
```python
import mysql.connector
# 连接数据库
cnx = mysql.connector.connect(user='username', password='password',
host='hostname',
database='databasename')
# 执行查询语句
cursor = cnx.cursor()
query = ("SELECT column1, column2 FROM tablename")
cursor.execute(query)
# 获取查询结果
for (column1, column2) in cursor:
# 处理每一行数据
print(column1, column2)
# 关闭数据库连接
cursor.close()
cnx.close()
```
在这个例子中,你需要将 `username`、`password`、`hostname` 和 `databasename` 替换为你实际使用的值。在执行查询语句后,你可以使用 `cursor` 对象来迭代每一行查询结果,并在需要时对其进行处理。最后,不要忘记关闭数据库连接以释放资源。
相关问题
python脚本连接数据库使用sql语句查询表数据
好的,您可以使用 Python 中的 `pymysql` 模块来连接 MySQL 数据库,并使用 SQL 语句查询表数据。以下是一个例子:
```python
import pymysql
# 连接数据库
db = pymysql.connect(host="localhost", user="username", password="password", database="database_name")
# 创建游标
cursor = db.cursor()
# 编写 SQL 语句
sql = "SELECT * FROM table_name WHERE column_name = 'value'"
# 执行 SQL 语句
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
# 遍历结果
for row in results:
# 输出每一行数据
print(row)
# 关闭游标和数据库连接
cursor.close()
db.close()
```
在代码中,您需要将 `host`、`user`、`password` 和 `database` 替换为您的 MySQL 数据库的实际信息,将 `table_name`、`column_name` 和 `value` 替换为您要查询的表、列和条件值。
python执行mysql数据库的sql语句,且sql语句是变量,表名和查询条件由外部传参
要执行MySQL数据库的SQL语句,可以使用Python的MySQL连接库,如`pymysql`或`mysql-connector-python`。以下是一个示例代码,演示如何执行可变的SQL语句,其中表名和查询条件由外部传递的参数指定。
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='username', password='password', db='database_name')
# 创建游标对象
cursor = conn.cursor()
def execute_sql(table_name, query_condition):
try:
# 构造SQL语句
sql = f"SELECT * FROM {table_name} WHERE {query_condition};"
# 执行SQL语句
cursor.execute(sql)
# 提取结果
results = cursor.fetchall()
# 输出结果
for row in results:
# 处理每一行数据
print(row)
except Exception as e:
print(f"Error: {e}")
finally:
# 关闭游标和数据库连接
cursor.close()
conn.close()
# 传递参数执行SQL语句
execute_sql("table_name", "column_name='value'") # 传递表名和查询条件作为参数
```
请注意,此处示例使用了f-string(Python 3.6以上版本)来构造SQL语句,确保在使用时替换`host`,`port`,`user`,`password`和`db`为相应的数据库连接参数,并根据需求修改SQL语句的构造方式和结果的处理方式。