Use Python to operate Mysql, and use Python to operate Mysql
The main programming language is Java, and Mysql is also used during development. for testing purposes, you often need to operate databases, such as backup, insert test data, and modify test data, in some cases, you cannot simply use SQL to complete the task or complete the task well. It is a little too troublesome to write in Java, so you can think of Python. The Python syntax is concise and does not need to be compiled. You can complete the task well. Today, I checked Python's operations on Mysql and made a record.
First of all, the environment required for installation is not mentioned in Mysql and Python.
The main installation of MySQLdb, you can go to sf.net download, the specific address is the http://sourceforge.net/projects/mysql-python/
If Ubuntu is used
Sudo apt-get install python-mysqldb
After the installation is complete, you can test it in the Python interpreter.
Input
Python code
- Import MySQLdb # case sensitive !!
If no error is reported, the installation is successful and may continue.
MySQLdb is equivalent to the JDBC Driver of MySQL in JAVA in Python. Python also has similar data interface specifications for Python db api. MySQLdb is the implementation of Mysql. The operation is also relatively simple, just like operating databases on other platforms or languages, that is, establishing a connection with the database system, then inputting SQL to the database, and then obtaining results from the database.
First, write the simplest one to create a database:
Python code
- #! /Usr/bin/env python
- # Coding = UTF-8
- ###################################
- # @ Author migle
- # @ Date 2010-01-17
- ##################################
- # MySQLdb example
- #
- ##################################
- Import MySQLdb
- # Establish a connection to the Database System
- Conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = 'longforfreedom ')
- # Retrieve operation cursor
- Cursor = conn. cursor ()
- # Execute SQL to create a database.
- Cursor.exe cute ("" create database python """)
- # Close the connection and release resources
- Cursor. close ();
Create databases, create tables, insert data, and insert multiple data records
Python code
- #! /Usr/bin/env python
- # Coding = UTF-8
- ###################################
- # @ Author migle
- # @ Date 2010-01-17
- ##################################
- # MySQLdb example
- #
- ##################################
- Import MySQLdb
- # Establish a connection to the Database System
- Conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = 'longforfreedom ')
- # Retrieve operation cursor
- Cursor = conn. cursor ()
- # Execute SQL to create a database.
- Cursor.exe cute ("" create database if not exists python """)
- # Selecting a database
- Conn. select_db ('python ');
- # Execute SQL to create a data table.
- Cursor.exe cute ("" create table test (id int, info varchar (100 ))""")
- Value = [1, "inserted? "];
- # Insert a record
- Cursor.exe cute ("insert into test values (% s, % s)", value );
- Values = []
- # Generating insert parameter values
- For I in range (20 ):
- Values. append (I, 'Hello mysqldb, I am recoder '+ str (I )))
- # Insert multiple records
- Cursor.exe cute.pdf ("" insert into test values (% s, % s) ", values );
- # Close the connection and release resources
- Cursor. close ();
The query process is similar to the insert process, but there is only one more step to get the query result.
Python code
- #! /Usr/bin/env python
- # Coding = UTF-8
- ######################################
- #
- # @ Author migle
- # @ Date 2010-01-17
- #
- ######################################
- #
- # MySQLdb Query
- #
- #######################################
- Import MySQLdb
- Conn = MySQLdb. connect (host = 'localhost', user = 'root', passwd = 'longforfreedom ', db = 'python ')
- Cursor = conn. cursor ()
- Count = cursor.exe cute ('select * from test ')
- Print 'total % s record records ', count
- # Obtain a record. Each record is returned as a tuples.
- Print "get only one record :"
- Result = cursor. fetchone ();
- Print result
- # Print 'id: % s info: % s' % (result [0], result [1])
- Print 'id: % s info: % s' % result
- # Obtain five records. Note that the cursor has pointed to the second record because fetchone () was previously executed, that is, all records starting from the second record.
- Print "get only five records :"
- Results = cursor. fetchtasks (5)
- For r in results:
- Print r
- Print "get all results :"
- # Reset the cursor position. The value 0 indicates the offset. mode = absolute | relative. The default value is relative,
- Cursor. scroll (0, mode = 'absolute ')
- # Getting all results
- Results = cursor. fetchall ()
- For r in results:
- Print r
- Conn. close ()
When you use python to operate MySQL, the data displayed on the python interface is changed, but the data is not changed when you access the View table from MySQL.
If you are using a database operated by MySQLdb, You need to commit after executing the SQL statement. Example:
Conn = MySQLdb. connect (user = 'xxx', db = 'xxx', passwd = 'xxx', host = '123. 0.0.1 ', use_unicode = True, charset = 'utf8 ')
Cur = conn. cursor ()
Cur.exe cute ('Update table set xxx = XXX ')
Conn. commit ()
Cur. close ()
Conn. close ()
Python mysql Operation Problems
Dict1 = self. fuc1 ()
Dict2 = self. fun2 ()
Def newdict (self ):
Dict = {}
For k, v in dict1.items ():
Dict [k] = v
For k1, v1 in dict2.items ():
Dict [k1] = v1
Return dict