Python operation MySQL

Source: Internet
Author: User

The

#coding =utf-8 Import MySQLdb conn = mysqldb.connect (host= ' localhost ', user= ' root ', passwd= ' 123456 ', charset= ' UTF8 ') cursor = Conn.cursor () Try: #创建数据库 db_name = ' test ' cursor.execute (' DROP DATABASE IF EXISTS%s '%db_name) curso R.execute (' CREATE DATABASE IF not EXISTS%s '%db_name) conn.select_db (db_name) #创建表 table_name = ' t_user ' cur    Sor.execute (' CREATE TABLE%s (ID int primary key,name varchar () '%table_name) #插入单条数据 value = [1, ' ALEXZHOU1 '] Cursor.execute (' INSERT into t_user values (%s,%s) ', value) #批量插入数据 the values = [] for I in range (2,10): Values . Append ((i, ' alexzhou%s '% (str (i)))) Cursor.executemany (' INSERT into t_user values (%s,%s) ', values) #查询记录数量 count = Cursor.execute (' SELECT * from%s '%table_name) print ' Total records:%d ', count #查询一条记录 print ' Fetch one record : ' result = Cursor.fetchone () print result print ' ID:%s,name:%s '% (result[0],result[1]) #查询多条记录 print ' F Etch five record: ' results = CURsor.fetchmany (5) for R in Results:print R #查询所有记录 #重置游标位置, offset: greater than 0 to move backwards, less than 0 to move forward, mode default is relative #relat Ive: Represents moving from the current line, absolute: means moving from the first line cursor.scroll (0,mode= ' absolute ') results = Cursor.fetchall () for R in Resul Ts:print R Cursor.scroll ( -2) results = Cursor.fetchall () for R in Results:print R #更新记录 C  Ursor.execute (' UPDATE%s SET name = '%s ' WHERE id =%s '% (table_name, ' Zhoujianghai ', 1) ') #删除记录 cursor.execute (' DELETE From%s WHERE id =%s '% (table_name,2) #必须提交, otherwise no data is inserted conn.commit () Except:import traceback traceback.print _exc () Conn.rollback () Finally:cursor.close () Conn.close ()

Original address: http://codingnow.cn/language/444.html

Python operation MySQL

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.