python 连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 |
结果:
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。1 2 3 4 5 6 | (u 'xiaoming' , 10 ) (u 'rose' , 18 ) (u 'jack' , 19 ) (u 'fang' , 20 ) (u 'Liang' , 40 ) (u 'Age' , No |

更多精彩