Python & Pandas link MySQL database

Source: Internet
Author: User

Python&pandas connection to MySQL

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

1 ImportMySQLdb2 3 Try:4 5conn = MySQLdb.connect (host='localhost', user='Root', passwd='xxxxx', db='Test', charset='UTF8')6 7Cur =conn.cursor ()8 9Cur.execute ('CREATE TABLE User (id int,name varchar )' )Ten  One     A  -Value = [1,'Jkmiao'] -  theCur.execute ("INSERT into user values (%s,%s)", value) -  -   -  +Users = [] -  +   A  at      forIinchRange (20): -  -Users.append ((I,"User"+str (i))) -  -   -  inCur.executemany ("INSERT into user values (%s,%s)", users) -  to   +  -Cur.execute ("Update user Set name="Test"where id=2") the  *    $ Panax Notoginsengres =Cur.fetchone () -  the     PrintRes +  A   the  +res = Cur.fetchmany (10) -  $     PrintRes $  -   -  the     PrintCur.fetchall () - Wuyi     the  - Conn.commit () Wu  - cur.close () About  $ conn.close () -  -Cur.execute ('SELECT * from user') -  A cur.close () +  the conn.close () -  $ exceptmysqldb.error,e: the  the      Print "Mysql Error%d:%s"% (E.args[0], e.args[1])

2. Pandas connection operation MySQL:

1 ImportPandas as PD2 3 ImportMySQLdb4 5  6 7conn = MySQLdb.connect (host="Localhot", user="Root", passwd="*****", db="Test", charset="UTF8")8 9  Ten  One #Read A  -sql ="SELECT * from user limit 3" -  theDF = Pd.read_sql (sql,conn,index_col="ID") -  - PrintDF -  +   -  + #Write A  atCur =conn.cursor () -  -Cur.execute ("drop table if exists user") -Cur.execute ('CREATE TABLE User (id int,name varchar )' ) -Pd.io.sql.write_frame (DF,"User", conn)

Python & Pandas link MySQL database

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.