python3连接Mysql数据库实例
2014-07-04 17:20
148 查看
// 准备工作, 在mysql网站上面下载
mysql-connector-python-1.1.6-py3.2.msi
#------------- 代码
mysql-connector-python-1.1.6-py3.2.msi
#------------- 代码
import mysql.connector import sys, os user = 'root' pwd = '123456' host = '127.0.0.1' db = 'test' data_file = 'mysql-test.dat' create_table_sql = "CREATE TABLE IF NOT EXISTS mytable ( \ id int(10) AUTO_INCREMENT PRIMARY KEY, \ name varchar(20), age int(4) ) \ CHARACTER SET utf8" insert_sql = "INSERT INTO mytable(name, age) VALUES ('Jay', 22 ), ('杰', 26)" select_sql = "SELECT id, name, age FROM mytable" cnx = mysql.connector.connect(user=user, password=pwd, host=host, database=db) cursor = cnx.cursor() try: cursor.execute(create_table_sql) except mysql.connector.Error as err: print("create table 'mytable' failed.") print("Error: {}".format(err.msg)) sys.exit() try: cursor.execute(insert_sql) except mysql.connector.Error as err: print("insert table 'mytable' failed.") print("Error: {}".format(err.msg)) sys.exit() if os.path.exists(data_file): myfile = open(data_file) lines = myfile.readlines() myfile.close() for line in lines: myset = line.split() sql = "INSERT INTO mytable (name, age) VALUES ('{}', {})".format(myset[0], myset[1]) try: cursor.execute(sql) except mysql.connector.Error as err: print("insert table 'mytable' from file 'mysql-test.dat' -- failed.") print("Error: {}".format(err.msg)) sys.exit() try: cursor.execute(select_sql) for (id, name, age) in cursor: print("ID:{} Name:{} Age:{}".format(id, name, age)) except mysql.connector.Error as err: print("query table 'mytable' failed.") print("Error: {}".format(err.msg)) sys.exit() cnx.commit() cursor.close() cnx.close()
相关文章推荐
- Silverlight中连接MySQL数据库实例详解
- PHP入门学习实例代码,代码例子–PHP连接mysql数据库
- PHP连接局域网MYSQL数据库的简单实例
- java web 程序---jsp连接mysql数据库的实例基础+表格显示
- Visual Studio 2005 连接mysql数据库实例
- Java 连接mysql数据库实例
- Python连接MySQL数据库通信实例以及中文乱码的解决办法
- .net连接MySQL数据库的方案与实例演示
- PHP连接局域网MYSQL数据库的实例
- java连接mysql数据库实例
- PHP入门学习实例代码,代码例子–PHP连接mysql数据库
- Java 通过JDBC连接Mysql数据库的方法和实例【图文说明】
- linux c 连接mysql数据库实例
- PHP连接局域网MYSQL数据库的简单实例
- php 连接mysql数据库并显示数据 实例 转载
- ODBC连接MySQL数据库操作实例
- 用C api 连接mysql数据库的 开发实例
- Qt数据库操作 连接SQLite和MySQL数据库实例
- qt连接mysql数据库实例
- Java使用jdbc连接MySQL数据库详细实例