Python-MySQL

###Python 使用MySQLdbsql

import MySQLdb

#鏈接MySQL \
# connect方法用於建立數據庫鏈接,裏面能夠指定參數,主機,用戶,密碼等。\
# 這只是鏈接到數據庫,想對數據庫進行操做,須要建立遊標
conn = MySQLdb.connect(host = '192.168.1.2',
                       user = 'root',
                       passwd = '123123',
                       port = 3306,
                       db = 'test')

#建立遊標
cur = conn.cursor()

#經過遊標cur操做execute方法能夠寫入sql語句
cur.execute("create table user(id int (11),  number int(11)")
 
#關閉遊標 \
#提交事務 \
#關閉數據庫鏈接
cur.close()
conn.commit()
conn.close()

####插入數據:數據庫

import MySQLdb

conn = MySQLdb.connect(host = '192.168.1.2',
                       user = 'root',
                       passwd = '123123',
                       port = 3306,
                       db = 'test')

cur = conn.cursor()
#一次插入多條紀錄
fs = 'insert into user(%s, %s)'
cur. executemany(fs, [
('1', '123'),
('2', '456'),
('3', '789')]
)


cur.close()
conn.commit()
conn.close()

####獲取MySQL數據fetch

import MySQLdb

conn = MySQLdb.connect(host = '192.168.1.2',
                       user = 'root',
                       passwd = '123123',
                       port = 3306,
                       db = 'test')

cur = conn.cursor()
#獲取表中多少條數據
fs = cur. execute('select * from user')
print fs

#打印表中多少條數據
info = cur. fetchmany(fs)
for line in info:
    print i

cur.close()
conn.commit()
conn.close()
相關文章
相關標籤/搜索