使用python中的mysql.connector模块操作mysql
python代码
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)
更加规范的操作,代码如下
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) # 将命令和参数分隔开,操作起来更加安全