Python3 link MySQL Database

Source: Internet
Author: User
Tags python script

There are quite a few libraries connected to MySQL on Python 2.x, the more famous of which is MySQLdb (the Django project uses it; I also used it when developing test systems), see: http://sourceforge.net/projects/mysql-python/

However, at present MYSQLDB does not support python3.x, the Internet to find some methods, and then I accidentally found that MySQL has been provided by the official MySQL connector, and already have a support python3.x version. MySQL Connector/python, a self-contained Python driver for communicating with MySQL servers. This is still more comfortable to use.
About MySQL Connector/python all kinds of introduction, installation, API and other documents, or reference official Internet cafes: http://dev.mysql.com/doc/connector-python/en/index.html
(Note: The installer has copied the source files for MySQL connnector Python2 to the location of the Python3 library (the runtime will report a syntax error), and I have directly copied the files in the python3/directory in the past to resolve them. )

In addition, python3.x connection to MySQL other programs are: Oursql, Pymysql, myconnpy, etc., refer to the following links:

http://packages.python.org/oursql/

https://github.com/petehunt/PyMySQL/

Https://launchpad.net/myconnpy

Here's just a Python script that tries MySQL Connector/python (including creating a table, inserting data, reading from a file, inserting data, querying data, and so on):

View Code PYTHON
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66
#!/usr/bin/python3# a sample to use Mysql-connector for python3# see details from HTTP://DEV.MYSQL.COM/DOC/CONNECTOR-PYT Hon/en/index.html import mysql.connectorimport sys, os user = ' root ' pwd = ' 123456 ' host = ' 127.0.0.1 ' db = ' tes T '  data_file = ' mysql-test.dat '  create_table_sql = "CREATE table IF not EXISTS mytable (ID Int (Ten) auto_increment PRIMARY KEY, name varchar (4), age int. CHARACTER SET UTF8 " insert_sql =" Insert I NTO MyTable (name, age) VALUES (' Jay ', 22), (' Jay ', ' + ') "Select_sql =" SELECT ID, Name, age from mytable " CNX = mysql.co Nnector.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 ER    R:print ("Insert Table ' mytable ' failed.") Print("Error: {}". Format (err.msg)) sys.exit ()  if os.path.exists (data_file): myfile = open (data_file) lines = Myfi  Le.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.ERR            Or 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 ()

Also, finally, put a python2.x code example that uses MYSQLDB:

View Code PYTHON
12345678910111213141516171819202122232425262728
#!/usr/bin/python2.7# coding=utf-8 import mysqldbimport sys host = ' localhost ' user = ' root ' pwd  = ' 123456 '   # to be Modified.db   = ' Test ' if __name__ = = ' __main__ ':    conn = MySQLdb.connect (host, user, PWD, db, charset= ' UTF8 ');    Try:        conn.ping ()    except:        print ' failed to connect MySQL. '    sql = ' SELECT * FROM mytable where id = 2 '    cur = conn.cursor ()    cur.execute (sql)    row = Cur.fetchone () #    Print type (row) for    i in row:        print I    cur.close ()    conn.close ()    sys.exit ()

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.