基于python和mysql的查询操作

1.当我们和数据库交互时,查询操作是必不可少的,下面我们来看下如何用python来对mysql数据库进行操作。

  1.1基本的查询操作:

select * from table1;查询表table1中的所有数据

select id from talbe1;查询表table1中包含id的数据

下面举例来看下基本操作

基于python和mysql的查询操作_第1张图片

  1.2 select和where连用,选择 artist_id=“‘61dfd882204789d7d0f70fee2b901cef”的所有song_id,一共12条记录,全部正确找出。

基于python和mysql的查询操作_第2张图片

2. 为了方便我们更好的说明查询操作,接下来我们新建一个mytest的数据库,并在库中放入表sqltest.

#coding:utf-8
#__author:dragon
import csv
import time
import pickle
import numpy as np
import matplotlib.pyplot as plt
import MySQLdb

def mysqlOperateFrist():
    conn = MySQLdb.connect(host='localhost',user='root',passwd='123',db='mytest',charset="utf8")
    curs = conn.cursor()
    sql = """create table sqltest ( song_id char(5) not null, artist_id char(5), publish_id tinyint, plays_id int, language tinyint, gender tinyint )"""


    # curs.execute(sql1)
    curs.execute(sql)
    curs.close()
    conn.close()

if __name__ == '__main__':
    mysqlOperateFrist()
    print 'OK'

2.1 在mysql中显示如sqltest,sql1.

基于python和mysql的查询操作_第3张图片

建立的两个这样的表

基于python和mysql的查询操作_第4张图片

基于python和mysql的查询操作_第5张图片

2.2 使用子查询实现多表检索,用子查询尽量不要去改变表的结构。

基于python和mysql的查询操作_第6张图片

2.3带关系比较运算符的子查询

基于python和mysql的查询操作_第7张图片

你可能感兴趣的:(数据库,mysql,python)