Python-mysql basic usage

Source: Internet
Author: User
Because the project database is to be transferred to MySQL, it took me an hour to understand the usage of Python-mysql. The following is a summary: #-*-coding: UTF-8-*-import mysqldb as mdbimport sys # Set con to global connection con = MDB. connect ('localhost', 'root', '', 'test'); with Con: # obtain the linked cursor, only the obtained cursor, we can perform various operations cur = con. cursor () # create a data table writers (ID, name) cur.exe cute ("create table if not exists \ writers (ID int primary key auto_increment, name varchar (25 ))") # insert 5 data records cur.exe cute ("Insert into writers (name) values ('Jack London ')") cur.exe cute ("insert into writers (name) values ('honore de balzac ')") cur.exe cute ("insert into writers (name) values ('lion feuchtwanger ')") cur.exe cute ("insert into writers (name) values ('emile Zola ')") cur.exe cute ("insert into writers (name) values ('Truman Capote')") Below we analyze the above Code: con = MDB. connect ('localhost', 'root', '', 'test');: This is used to connect to the local 'T' Est 'database, 'root' is the username of the local database, and ''is the password of this user. We leave the password empty here. Cur = con. cursor (): Obtain the connected cursor, so that we can use cur to call the command import mysqldb as MDB later: to import a mysqldb module named "mdb. Import mysqldb as mdbimport syscon = MDB. connect ('localhost', 'root', '', 'test'); with Con: cur = con. cursor () cur.exe cute ("select * from writers") ''' rows = cur. fetchall () for row in rows: Print row ''' numrows = int (cur. rowcount) for I in range (numrows): ROW = cur. fetchone () print row [0], row [1]

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.