admin 管理员组

文章数量: 1184232


2024年4月25日发(作者:emptying)

python mysql查询语句

Python是一种广泛使用的编程语言,而MySQL是一种流行的关

系型数据库管理系统。在Python中,可以使用MySQLdb模块来连接

MySQL数据库,并执行查询语句。

以下是一些常见的MySQL查询语句,可以在Python中使用:

1. SELECT语句:用于从数据库中查询数据。例如:

```

import MySQLdb

# 连接数据库

db = t(host='localhost', user='root',

passwd='password', db='test')

# 创建游标

cursor = ()

# 执行查询

e('SELECT * FROM students')

# 获取结果

results = ll()

# 输出结果

for row in results:

print(row)

```

2. WHERE语句:用于筛选符合条件的数据。例如:

- 1 -

```

import MySQLdb

# 连接数据库

db = t(host='localhost', user='root',

passwd='password', db='test')

# 创建游标

cursor = ()

# 执行查询

e('SELECT * FROM students WHERE age > 18')

# 获取结果

results = ll()

# 输出结果

for row in results:

print(row)

```

3. INSERT语句:用于向数据库中添加数据。例如:

```

import MySQLdb

# 连接数据库

db = t(host='localhost', user='root',

passwd='password', db='test')

# 创建游标

- 2 -

cursor = ()

# 执行插入

e('INSERT INTO students(name, age)

VALUES('Tom', 20)')

# 提交更改

()

```

4. UPDATE语句:用于更新数据库中的数据。例如:

```

import MySQLdb

# 连接数据库

db = t(host='localhost', user='root',

passwd='password', db='test')

# 创建游标

cursor = ()

# 执行更新

e('UPDATE students SET age = 21 WHERE name =

'Tom'')

# 提交更改

()

```

5. DELETE语句:用于从数据库中删除数据。例如:

- 3 -

```

import MySQLdb

# 连接数据库

db = t(host='localhost', user='root',

passwd='password', db='test')

# 创建游标

cursor = ()

# 执行删除

e('DELETE FROM students WHERE name = 'Tom'')

# 提交更改

()

```

以上是一些常见的MySQL查询语句,在Python中使用MySQLdb

模块进行连接和操作。可以根据需要进行调整和扩展,以满足不同的

需求。

- 4 -


本文标签: 数据库 语句 数据 用于 连接