mysql与python的交互

##导包
import pymysql

#封装方法
def main():
    #创建mysql连接
    conn = pymysql.connect(host='localhost',port=3306,database='python01',user='root',password='858362',charset='utf8')
    #创建cursor,接受mysql语句并且执行的对象方法
    cursor = conn.cursor()
    #插入10万数据
    for x in range(100000):
        cursor.execute("insert into test_index values('ha - %s','ca - %s')"%(x,x))
    conn.commit()

if __name__ == '__main__':
    main()
import pymysql

def test():
    conn=pymysql.connect(host='localhost',port=3306,database='message',user='root',password='858362',charset='utf8')
    cursor=conn.cursor()

    cursor.execute('select * from classify')

    ret=cursor.fetchall()
    print(ret)
    cursor.execute('select * from news where id = 1')
    r=cursor.fetchone()
    print(r)
    cursor.execute('delete from news where id = 2')
    cursor.execute('select * from news')
    e=cursor.fetchall()
    print(e)
    cursor.execute('update news set name = "张三" where id = 3')
    cursor.execute('select * from news where id = 3')
    a=cursor.fetchone()
    print(a)
    cursor.execute('select * from news where s_news = 1')
    vv=cursor.fetchall()
    print(vv)
    cursor.execute('select * from news where (count>5 and is_delete = "是")')
    ew=cursor.fetchone()
    print(ew)
    conn.commit()
    cursor.close()
    conn.close()

if __name__ == '__main__':
    test()
import pymysql
#
# #创建函数
def main():
    #建立mysql连接
    conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='858362',database='python01',charset='utf8')
    #创建cursor对象,执行sql语句,声明游标对象返回dict
    cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)

    cursor.execute("select * from students")#select * from students
    ret=cursor.fetchone()
    # ret=cursor.fetchall()
    # print(ret)
    # print(ret[4])
    # print(ret[4]['name'])
    print(ret['name'])
    cursor.close()
    conn.close()
if __name__ == '__main__':
    main()

 

posted @ 2018-12-06 11:18  寒风孤影,江湖故人  阅读(278)  评论(0编辑  收藏  举报