How to connect python to mysql
How to connect python to mysql? Here is a detailed introduction to how to use MySQLdb:
(1) What is MySQLdb?
MySQLdb is an interface for Python to connect to the MySQL database. It implements the Python database API specification V2.0 and is based on the MySQL C API.
(2) Install MySQLdb from source code: https://pypi.python.org/pypi/MySQL-python
$ tar zxvf MySQL-python-*.tar.gz $ cd MySQL-python-* $ python setup.py build $ python setup.py install
Related recommendations: "Python Video Tutorial"
(3) Use of MySQLdb:
#!/usr/bin/env python # coding=utf-8 import MySQLdb def connectdb(): print('连接到mysql服务器...') # 打开数据库连接 # 用户名:hp, 密码:Hp12345.,用户名和密码需要改成你自己的mysql用户名和密码,并且要创建数据库TESTDB, 并在TESTDB数据库中创建好表Student db = MySQLdb.connect("localhost","hp","Hp12345.","TESTDB") print('连接上了!') return db def createtable(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # 如果存在表Sutdent先删除 cursor.execute("DROP TABLE IF EXISTS Student") sql = """CREATE TABLE Student ( ID CHAR(10) NOT NULL, Name CHAR(8), Grade INT )""" # 创建Sutdent表 cursor.execute(sql) def insertdb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = """INSERT INTO Student VALUES ('001', 'CZQ', 70), ('002', 'LHQ', 80), ('003', 'MQ', 90), ('004', 'WH', 80), ('005', 'HP', 70), ('006', 'YF', 66), ('007', 'TEST', 100)""" #sql = "INSERT INTO Student(ID, Name, Grade) \ # VALUES ('%s', '%s', '%d')" % \ # ('001', 'HP', 60) try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # Rollback in case there is any error print '插入数据失败!' db.rollback() def querydb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 查询语句 #sql = "SELECT * FROM Student \ # WHERE Grade > '%d'" % (80) sql = "SELECT * FROM Student" try: # 执行SQL语句 cursor.execute(sql) # 获取所有记录列表 results = cursor.fetchall() for row in results: ID = row[0] Name = row[1] Grade = row[2] # 打印结果 print "ID: %s, Name: %s, Grade: %d" % \ (ID, Name, Grade) except: print "Error: unable to fecth data" def deletedb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 删除语句 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100) try: # 执行SQL语句 cursor.execute(sql) # 提交修改 db.commit() except: print '删除数据失败!' # 发生错误时回滚 db.rollback() def updatedb(db): # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 更新语句 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003') try: # 执行SQL语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: print '更新数据失败!' # 发生错误时回滚 db.rollback() def closedb(db): db.close() def main(): db = connectdb() # 连接MySQL数据库 createtable(db) # 创建表 insertdb(db) # 插入数据 print '\n插入数据后:' querydb(db) deletedb(db) # 删除数据 print '\n删除数据后:' querydb(db) updatedb(db) # 更新数据 print '\n更新数据后:' querydb(db) closedb(db) # 关闭数据库 if __name__ == '__main__': main()
The above is the detailed content of How to connect python to mysql. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

Depending on the specific needs and project size, choose the most suitable IDE: large projects (especially C#, C) and complex debugging: Visual Studio, which provides powerful debugging capabilities and perfect support for large projects. Small projects, rapid prototyping, low configuration machines: VS Code, lightweight, fast startup speed, low resource utilization, and extremely high scalability. Ultimately, by trying and experiencing VS Code and Visual Studio, you can find the best solution for you. You can even consider using both for the best results.

The main differences between VS Code and PyCharm are: 1. Extensibility: VS Code is highly scalable and has a rich plug-in market, while PyCharm has wider functions by default; 2. Price: VS Code is free and open source, and PyCharm is paid for professional version; 3. User interface: VS Code is modern and friendly, and PyCharm is more complex; 4. Code navigation: VS Code is suitable for small projects, and PyCharm is more suitable for large projects; 5. Debugging: VS Code is basic, and PyCharm is more powerful; 6. Code refactoring: VS Code is basic, and PyCharm is richer; 7. Code
