python connects to mysql instance sharing

  • 2020-05-12 02:50:23
  • OfStack

Example 1


#coding=UTF-8

import sys
import MySQLdb
import time

reload(sys)
sys.setdefaultencoding('utf-8')

def connectDemo():
  return MySQLdb.Connection("127.0.0.1","root","root","demo",3306,charset="utf8")


if __name__ == '__main__':
  begin=time.time()

  conn=connectDemo()
  cursor = conn.cursor()
  sql="""
    show tables
    """
  count = cursor.execute(sql)
  rows = cursor.fetchall()
  cursor.close()
  conn.close()
  print "========demo Library, :%s  table ============" % (count)

  print ' Time consuming :%s  seconds ' % (time.time()-begin)

Example 2


import MySQLdb
conn = MySQLdb.connect(host="localhost",
user="root",
passwd="123456",
db="test")
cursor = conn.cursor()
cursor.execute("select * from hard")
res = cursor.fetchall()
for x in res:
print x
cursor.close()
conn.close()

Example 3

Install the Mysql package for Python


root@10.1.1.45:~# apt-get install python-mysqldb 
root@10.1.1.45:~# python 
Python 2.5.2 (r252:60911, Jan 4 2009, 21:59:32)  
[GCC 4.3.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import MySQLdb 
>>> 

If there is no error in importing MySQLdb, the installation is successful.

The following 2 can be connected to the database, you can change the operation.


root@10.1.1.45:python# cat create.py  
#!/usr/bin/env python 
#coding=utf-8 
 
# Import related modules  
import MySQLdb 
 
# Set up and mysql Database connection  
conn = MySQLdb.connect(host='localhost',user='root',passwd='davehe') 
# To obtain the cursor  
curs = conn.cursor() 
# perform SQL, create 1 A database  
curs.execute("create database pythondb") 
# Select which database to connect to  
conn.select_db('pythondb') 
# perform SQL, create 1 A table  
curs.execute("create table test(id int,message varchar(50))") 
# insert 1 records  
value = [1,"davehe"] 
curs.execute("insert into test values(%s,%s)",value) 
# Insert multiple records  
values = [] 
for i in range(20): 
  values.append((i,'hello mysqldb' + str(i))) 
curs.executemany("insert into test values(%s,%s)",values) 
# Commit changes                  
conn.commit() 
# Close cursor connection , Release resources  
curs.close() 
# Close the connection  
conn.close() 
root@10.1.1.45:python# ./create.py 

3. Use python to view the record just added in mysql.


root@10.1.1.45:python# cat select.py  
#!/usr/bin/env python 
#coding=utf-8 
 
# Import related modules  
import MySQLdb 
 
# Set up and mysql Database connection  
conn = MySQLdb.connect(host='localhost',user='root',passwd='hc1226') 
# To obtain the cursor  
curs = conn.cursor() 
# Select which database to connect to  
conn.select_db('pythondb') 
# See how many records there are  
count = curs.execute('select * from test') 
print "1 A total of %s records " % count 
# To obtain 1 records , In order to 1 Returns a tuple  
result = curs.fetchone() 
print " The current 1 records  ID:%s message:%s" % result 
# After obtaining 10 records , Because it was executed before getchone(), So the cursor is already at point 1 2 records , So let's start at number one 2 A record begins to return  
results = curs.fetchmany(10) 
for r in results: 
  print r 
# Reset cursor position ,0, To offset ,mode = relative( The default ) 
curs.scroll(0,mode='absolute') 
# Get all the records  
results = curs.fetchall() 
for r in results: 
  print r 
 
# Commit changes  
conn.commit() 
# Close cursor connection , Release resources  
curs.close() 
# Close the connection  
conn.close() 


root@10.1.1.45:python# ./select.py  
1 A total of 21 records  
 The current 1 records  ID:1 message:davehe 
(0L, 'hello mysqldb0') 
(1L, 'hello mysqldb1') 
(2L, 'hello mysqldb2') 
(3L, 'hello mysqldb3') 
(4L, 'hello mysqldb4') 
(5L, 'hello mysqldb5') 
(6L, 'hello mysqldb6') 
(7L, 'hello mysqldb7') 
(8L, 'hello mysqldb8') 
(9L, 'hello mysqldb9') 
(1L, 'davehe') 
(0L, 'hello mysqldb0') 
(1L, 'hello mysqldb1') 
(2L, 'hello mysqldb2') 
(3L, 'hello mysqldb3') 
(4L, 'hello mysqldb4') 
(5L, 'hello mysqldb5') 
(6L, 'hello mysqldb6') 
(7L, 'hello mysqldb7') 
(8L, 'hello mysqldb8') 
(9L, 'hello mysqldb9') 
(10L, 'hello mysqldb10') 
(11L, 'hello mysqldb11') 
(12L, 'hello mysqldb12') 
(13L, 'hello mysqldb13') 
(14L, 'hello mysqldb14') 
(15L, 'hello mysqldb15') 
(16L, 'hello mysqldb16') 
(17L, 'hello mysqldb17') 
(18L, 'hello mysqldb18') 
(19L, 'hello mysqldb19') 


Related articles: