One, install mysql
If you are a windows user, the installation of mysql is very simple, you can directly download the installation file, double-click the installation file, and operate step by step.
The installation under Linux may be simpler. In addition to downloading the installation package for installation, there will be mysql in general linux warehouses. We only need to download and install with one command:
Ubuntu\deepin
>>sudo apt-get install mysql-server
>>Sudo apt-get install mysql-client
centOS/redhat
>>yum install mysql
Second, install MySQL-python
In order for python to operate mysql, the MySQL-python driver is required, which is an indispensable module for python to operate mysql.
Download address: https://pypi.python.org/pypi/MySQL-python/
Download the MySQL-python-1.2.5.zip file and unzip it directly. Enter the MySQL-python-1.2.5 directory:
>>python setup.py install
Three, test
The test is very simple, check whether the MySQLdb module can be imported normally.
fnngj @ fnngj-H24X: ~ / pyse $ python Python 2.7.4 (default, Sep 26 2013, 03:20:56) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb
There is no error message indicating that the MySQLdb module cannot be found, indicating that the installation is OK. Before starting to use python to operate the database, it is necessary for us to review the basic operations of mysql:
Fourth, the basic operation of mysql
$ mysql -u root -p (when there is a password)
$ mysql -u root (when no password)
mysql> show databases; // View all current databases +--------------------+ | Database | +--------------------+ | information_schema | | csvt | | csvt04 | | mysql | | performance_schema | | test | +--------------------+ 6 rows in set (0.18 sec) mysql> use test; // function and test database Database changed mysql> show tables; //View the tables under the test library Empty set (0.00 sec) //Create a user table with two fields, name and password mysql> CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); Query OK, 0 rows affected (0.27 sec) //Insert several pieces of data into the user table mysql> insert into user values('Tom','1321'); Query OK, 1 row affected (0.05 sec) mysql> insert into user values('Alen','7875'); Query OK, 1 row affected (0.08 sec) mysql> insert into user values('Jack','7455'); Query OK, 1 row affected (0.04 sec) //View the data of the user table mysql> select * from user; +------+----------+ | name | password | +------+----------+ | Tom | 1321 | | Alen | 7875 | | Jack | 7455 | +------+----------+ 3 rows in set (0.01 sec) //Delete the data whose name is equal to Jack mysql> delete from user where name = 'Jack'; Query OK, 1 rows affected (0.06 sec) //Modify the password of name equal to Alen to 1111 mysql> update user set password='1111' where name = 'Alen'; Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0 // view table content mysql> select * from user; +--------+----------+ | name | password | +--------+----------+ | Tom | 1321 | | Alen | 1111 | +--------+----------+ 3 rows in set (0.00 sec)
Five, python operation mysql database foundation
#coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #create data table #cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))") #Insert a piece of data #cur.execute("insert into student values('2','Tom','3 year 2 class','9')") #Modify the data of the query condition #cur.execute("update student set class='3 year 1 class' where name = 'Tom'") #delete the data of the query condition #cur.execute("delete from student where age='9'") cur.close() conn.commit() conn.close()
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
The Connect() method is used to create a database connection, in which parameters can be specified: username, password, host and other information.
This is just a connection to the database. To operate the database, you need to create a cursor.
>>> cur = conn.cursor()
The cursor is created by the cursor() method under the obtained database connection conn.
>>> cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
The pure SQL statement can be written through the cursor cur operation execute() method. The data is manipulated by writing sql statements in the execute() method.
>>>cur.close()
cur.close() closes the cursor
>>>conn.commit()
The conn.commit() method commits things, and must have this method when inserting a piece of data into the database, otherwise the data will not be really inserted.
>>>conn.close()
Conn.close() closes the database connection
Six, insert data
It is not convenient to insert data by writing pure SQL statements in the execute() method above. Such as:
>>>cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
If I want to insert new data, I must modify the value in this statement. We can make the following modifications:
#coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #Insert a piece of data sqli="insert into student values(%s,%s,%s,%s)" cur.execute(sqli,('3','Huhu','2 year 1 class','7')) cur.close() conn.commit() conn.close()
What if you want to insert multiple values into the data table at once?
#coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #Insert multiple records at once sqli="insert into student values(%s,%s,%s,%s)" cur.executemany(sqli,[ ('3','Tom','1 year 1 class','6'), ('3','Jack','2 year 1 class','7'), ('3','Yaheng','2 year 2 class','7'), ]) cur.close() conn.commit() conn.close()
The executemany() method can insert multiple values at a time, execute the single-shot sql statement, but repeatedly execute the parameters in the parameter list, and the return value is the number of affected rows.
Seven, query data
Maybe you have tried in python via
>>>cur.execute("select * from student")
to query the data in the data table, but it did not print the data in the table, a little disappointed.
Let's see what this statement gets
>>>aa=cur.execute("select * from student")
>>>print aa
5
All it gets is how many pieces of data are in our table. How can I get the data in the table? enter python shell
>>> import MySQLdb >>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',) >>> cur = conn.cursor() >>> cur.execute("select * from student") 5L >>> cur.fetchone() (1L, 'Alen', '1 year 2 class', '6') >>> cur.fetchone() (3L, 'Huhu', '2 year 1 class', '7') >>> cur.fetchone() (3L, 'Tom', '1 year 1 class', '6') ... >>>cur.scroll(0,'absolute')
The fetchone() method can help us obtain the data in the table, but the data obtained by executing cur.fetchone() is different each time. In other words, if I did not execute it once, the cursor will move from the first data in the table to the next The location of a piece of data, so when I execute it again, I get the second piece of data.
The scroll(0,'absolute') method can position the cursor to the first piece of data in the table.
Still haven't solved the result we want, how to get multiple pieces of data in the table and print them out?
#coding=utf-8 import MySQLdb conn= MySQLdb.connect( host='localhost', port = 3306, user='root', passwd='123456', db ='test', ) cur = conn.cursor() #Get how many data in the table aa=cur.execute("select * from student") print aa # print how much data in the table info = cur.fetchmany(aa) for ii in info: print ii cur.close() conn.commit() conn.close()
Through the previous print aa, we know that there are 5 pieces of data in the current table. The fetchmany() method can obtain multiple pieces of data, but we need to specify the number of pieces of data, and we can print out multiple pieces of data through a for loop! The execution result is as follows:
5 (1L, 'Alen', '1 year 2 class', '6') (3L, 'Huhu', '2 year 1 class', '7') (3L, 'Tom', '1 year 1 class', '6') (3L, 'Jack', '2 year 1 class', '7') (3L, 'Yaheng', '2 year 2 class', '7') [Finished in 0.1s]