A.下載mysql-connector-python-2.1.6-py2.7-winx64.msi,下載以後,根據提示安裝便可html
下載地址:https://dev.mysql.com/downloads/connector/python/python
A.進入數據庫命令行操做界面,使用mysql -u USERNAME -p PASSWORDmysql
B.數據庫經常使用操做sql
show databases; # 顯示全部數據庫 create database t1; # 建立數據庫t1 use database t1; #指定當前操做的數據庫爲t1 drop database t1; #刪除數據庫t1
注:操做數據庫,可參考菜鳥教程http://www.runoob.com/mysql/mysql-tutorial.html數據庫
C.表中全部數據以下安全
python代碼spa
import mysql.connector # mysql1.py config = { 'host': '127.0.0.1', 'user': 'root', 'password': 'root', 'port': 3306, 'database': 'test', 'charset': 'utf8' } try: cnn = mysql.connector.connect(**config) except mysql.connector.Error as e: print('connect fails!{}'.format(e)) cursor = cnn.cursor() try: sql_query = 'select name,age from stu ;' cursor.execute(sql_query) for name, age in cursor: print (name, age) except mysql.connector.Error as e: print('query error!{}'.format(e)) finally: cursor.close() cnn.close()
操做結果命令行
(u'xiaoming', 10) (u'rose', 18) (u'jack', 19) (u'fang', 20) (u'Liang', 40) (u'Age', None)
更加規範的操做,代碼以下3d
def select2(sql_cmd, param): """ :param sql_cmd sql 命令 :param param 參數 """ try: conn = mysql.connector.connect(**config) except mysql.connector.Error as e: print('connect fails!{}'.format(e)) cursor = conn.cursor() try: cursor.execute(sql_cmd, param) except mysql.connector.Error as e: print('connect fails!{}'.format(e)) finally: cursor.close() conn.close() if __name__ == '__main__': sql_cmd = "insert into stu (name, age, sex) value (%s, %s, %s)" param = ('yangguo', 28, 'male') select2(sql_cmd=sql_cmd, param=param) # 將命令和參數分隔開,操做起來更加安全