標籤:str close ref mysqld .exe div connector 錯誤 style
1.安裝驅動
目前有兩個MySQ的L驅動,我們可以選擇其中一個進行安裝:
MySQL-python:是封裝了MySQL C驅動的Python驅動;mysql-connector-python:是MySQL官方的純Python驅動。
MySQL-python:
安裝教程:http://www.cnblogs.com/jfl-xx/p/7299221.html
mysql-connector-python:
安裝教程:http://www.cnblogs.com/Bgod/p/6995601.html
2.測試連接
這裡使用MySQL-python驅動,即MySQLdb模組。
test_connect.py
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 import MySQLdb 5 6 # 開啟資料庫連接 7 db = MySQLdb.connect("localhost", "root", "123456", "test") 8 9 # 使用cursor()方法擷取操作遊標10 cursor = db.cursor()11 12 # 使用execute方法執行SQL語句13 cursor.execute("SELECT VERSION()")14 15 # 使用 fetchone() 方法擷取一條資料庫。16 data = cursor.fetchone()17 18 print "Database version : %s " % data19 20 # 關閉資料庫連接21 db.close()
測試結果如下,串連成功:
3.建立資料庫表
測試成功後,我們可以在python中直接為MySQL建立表:
create_table.py
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 import MySQLdb 5 6 # 開啟資料庫連接 7 db = MySQLdb.connect("localhost", "root", "123456", "test") 8 9 # 使用cursor()方法擷取操作遊標10 cursor = db.cursor()11 12 # 如果資料表已經存在使用 execute() 方法刪除表。13 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")14 15 # 建立資料表SQL語句16 sql = """CREATE TABLE EMPLOYEE (17 FIRST_NAME CHAR(20) NOT NULL,18 LAST_NAME CHAR(20),19 AGE INT, 20 SEX CHAR(1),21 INCOME FLOAT )"""22 23 cursor.execute(sql)24 25 # 關閉資料庫連接26 db.close()
建表結果 如下:
4.操作資料庫表
注意點:MySQL中的預留位置為%s
operate_table.js
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 import MySQLdb 5 6 # 開啟資料庫連接 7 db = MySQLdb.connect("localhost", "root", "123456", "test") 8 9 # 使用cursor()方法擷取操作遊標10 cursor = db.cursor()11 12 # SQL插入語句13 ins_sql = """INSERT INTO EMPLOYEE(FIRST_NAME,14 LAST_NAME, AGE, SEX, INCOME)15 VALUES (‘yu‘, ‘jie‘, 20, ‘M‘, 8000)"""16 17 ins_sql1 = ‘insert into employee(first_name, last_name, age, sex, income) values (%s, %s, %s, %s, %s)‘18 19 # SQL查詢語句20 sel_sql = ‘select * from employee where first_name = %s‘21 22 # SQL更新語句23 upd_sql = ‘update employee set age = %s where sex = %s‘24 25 # SQL刪除語句26 del_sql = ‘delete from employee where first_name = %s‘27 28 try:29 # 執行sql語句30 # insert31 cursor.execute(ins_sql)32 cursor.execute(ins_sql1, (‘xu‘, ‘f‘, 20, ‘M‘, 8000))33 # select34 cursor.execute(sel_sql, (‘yu‘,))35 values = cursor.fetchall()36 print values37 # update38 cursor.execute(upd_sql, (24, ‘M‘,))39 # delete40 cursor.execute(del_sql, (‘xu‘,))41 42 # 提交到資料庫執行43 db.commit()44 except:45 # 發生錯誤時復原46 db.rollback()47 48 # 關閉資料庫連接49 db.close()
執行插入操作
執行查詢操作
執行更新操作
執行刪除操作
查詢語句的知識點:
Python查詢Mysql使用 fetchone() 方法擷取單條資料, 使用fetchall() 方法擷取多條資料。
fetchone(): 該方法擷取下一個查詢結果集。結果集是一個對象
fetchall():接收全部的返回結果行.
例如該例子:
1 sel_sql = ‘select * from employee where first_name = %s‘ 2 cursor.execute(sel_sql, (‘yu‘,)) 3 results = cursor.fetchall() 4 for row in results: 5 fname = row[0] 6 lname = row[1] 7 age = row[2] 8 sex = row[3] 9 income = row[4]10 print "fname=%s, lname=%s,age=%d,sex=%s,income=%d" % (fname, lname, age, sex, income)
結果如下:
python串連MySQL