Step 1: connect
Import MySQLdb # first, you need to introduce mysqldb, that is, the module connecting Python to MySQL. Conn = MySQLdb. connect (host = "localhost", user = "root", passwd = "") # This is equivalent to the default value: conn = MySQLdb. connect () cur = conn. cursor () # create a cursor for sending SQL commands
In this way, you can use the cursor cur to send SQL commands to mysql.
Step 2: Operation
1. Create a database
cur.execute('create database adams')
Check it again in mysql. Of course, you can also view it directly in python, but here we will write about how to view it in mysql to facilitate the conversion of the two environments.
2. Create a table
Cur.exe cute ('use Adams') directly connects to use the data library adamsand MySQL usage method cur.exe cute ('create table test (ID int, name varchar (8), sex varchar(1+'{cur.exe cute ('show table ') # You cannot print the tables directly here, but use the following command to view the cur. fetchone ()
The following result is displayed:
Vc/J2aOsu/fuse + CjxwPjwvcD4KPHByZSBjbGFzcz0 = "brush: java;"> sqlim = "insert into test (ID, name, sex) values (% s, % s, % s) "# Write down the SQL statement and use the formatting method to pass in variable values. Note that % sm1 = (1, 'aaa', 'F') is used no matter what data type ') m2 = (2, 'bbb ', 'M') m3 = (3, 'ccc', 'M') m4 = (4, 'ddd ', 'F ') m5 = (5, 'eee', 'm'{cur.exe cute.pdf (sqlim, [m1, m2, m3, m4, m5]) # Run the five values and SQL commands in the list using the execute.pdf command. If there is only one value, change executeparameters to execute and change values in sqlim to value. You can pass in an m parameter.
3. 2. Query
cur.execute('select * from test')cur.fetchall()
The following result is displayed.
Here, the pointer is moved to the end and no result is obtained after cur. fetchone () is executed. Therefore, the pointer needs to be moved.
Cur. scroll (offset, mode) # The usage of this scroll is the same as that of the seek function used for file operations in python. mode = absolute "relative, which is relative by default.
We move the cur to the beginning.
Cur. scroll (0, 'absolute ') cur. catchroll (2) # Check the first two pieces of data.
Because the number of records in test is obtained by cur.exe cute ('select * from test'), you can directly output all entries.
cur.catchmany(cur.execute('select * from test'))
Step 3: Exit
Exit the cursor first
cur.close()
Exit the connection
conn.close()
Statement
This article is a crazy Python in the Yiyun classroom of the listening Network: Quick Start lecture notes made in Lesson 37th.