This article describes how Python accesses the MySQL database. Share to everyone for your reference, as follows:
First install the mysqldb that matches the Python version
Example One
Import Mysqldbconn=mysqldb.connect (user= ' root ', passwd= ' 123 ', db= ' example ') cur=conn.cursor () Cur.execute ("SELECT ID , Lastname,firstname, Date_format (DOB, '%y-%m-%d%h-%i-%s '), phone from employee ") # #select Username,password, Date_ Format (reg_date, '%y-%m-%d%h-%i-%s ') as date from reg_userfor data in Cur.fetchall (): print Datacur.close () Conn.commit () Conn.close ()
Example Two
Import Mysqldbconn = MySQLdb.connect (host= ' localhost ', user= ' root ', passwd= ') cursor = Conn.cursor () cursor.execute (" Create Database Python ") cursor.execute (' Use Python ') cursor.execute (" CREATE TABLE test (ID int, content varchar (100)) ") # Insert a 100 data for I in range (1,100): cursor.execute ("INSERT into test values (%s,%s)", [I, ' haha ']) #获取数据cursor. Execute ( ' SELECT * from Test ') results = Cursor.fetchall () for R in results print rconn.close ()
I hope this article is helpful for Python program design.