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()
相關文章
相關標籤/搜索