Python&pandas connection to MySQL

Source: Internet
Author: User

1. Python and MySQL connection and operation, directly on the code, simple and direct efficiency:

Import MySQLdbTry: Conn= MySQLdb.connect (host='localhost', user='Root', passwd='xxxxx', db='Test', charset='UTF8') cur=conn.cursor () Cur.execute ('CREATE TABLE User (id int,name varchar )') Value= [1,'Jkmiao'] Cur.execute ("INSERT into user values (%s,%s)", value) users= []     forIinchRange -): Users.append ((i,"User"+str (i))) Cur.executemany ("INSERT into user values (%s,%s)", users) Cur.execute ("Update user Set name="Test"where id=2") Res=Cur.fetchone () Print res res= Cur.fetchmany (Ten) Print res print cur.fetchall () conn.commit () Cur.close () Conn.close () Cur.execute ('SELECT * from user') Cur.close () conn.close () except Mysqldb.error,e:print"Mysql Error%d:%s"% (e.args[0], e.args[1])

2. Pandas connection Operation MySQL

ImportPandas as PDImportMysqldbconn= MySQLdb.connect (host="Localhot", user="Root", passwd="*****", db="Test", charset="UTF8")#Readsql ="SELECT * from user limit 3"DF= Pd.read_sql (sql,conn,index_col="ID")PrintDF#WriteCur =conn.cursor () Cur.execute ("drop table if exists user")
Cur.execute (' CREATE table user (ID int,name varchar (20)) ')
pd.io.sql.write_frame (DF,"User", conn)

Python&pandas connection to MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.