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