IT tutorials
 
Database
 

MySQL for Python : Simple Insertion - Passing an insertion through MySQL for Python

1/23/2013 11:37:18 AM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019

Inserting data into MySQL is a straightforward process that is largely based around ensuring that the database daemon knows where you want your data placed. Inserting data into MySQL may seem a bit more complicated than retrieving it but the previous discussion shows it is still logical, but just requires a few more keywords in order to be useful.

Setting up the preliminaries

Using INSERT with MySQL for Python is just as easy as using SELECT. We pass the command to MySQL using the execute() method of the database cursor object.

We will again use the fish database and the menu table as follows:

+----+----------------+-------+
| id | name | price |
+----+----------------+-------+
| 1 | tuna | 7.50 |
| 2 | bass | 6.75 |
| 3 | salmon | 9.50 |
| 4 | catfish | 5.00 |
| 5 | trout | 6.00 |
| 6 | haddock | 6.50 |
| 7 | yellowfin tuna | 12.00 |

Once again, we need to set up the database objects in our Python session . Close the session by pressing Ctrl+D and initiate a new one. Then import MySQL for Python, tend to the database login and create the cursor object as follows:

import MySQLdb
mydb = MySQLdb.connect(host = 'localhost', user = 'skipper',
passwd = 'mysecret',
db = 'fish')
cur = mydb.cursor()

Now we are ready to insert data using Python.

A simple INSERT statement

Inserting data through MySQL for Python uses the same method as retrieving it using execute(). You will recall that data retrieval using MySQL for Python follows this formula:

results_variable = cursor_handle.execute('MySQL SELECT statement')

And so one gets a Python statement that looks like the following:

command = cur.execute('SELECT * FROM menu')

The main difference in data insertion is that no values are being returned. Therefore, because we are not retrieving any data, we do not need to assign the value of returning data to a variable. Instead, we pass the insertion command as a stand-alone command.

The basic system call for the insertion command would follow this template:

cursor_handle.execute('MySQL INSERT statement')

Using this template, we can pass the following MySQL INSERT statement:

INSERT INTO menu(name, price) VALUES("shark", "13.00");

Without worrying about validating the integrity of the data for the moment, we insert this statement through MySQL for Python as follows (using the cursor object cur as defined previously):

cur.execute("""INSERT INTO menu(name, price) VALUES("shark", "13.00")""")

Of course, this statement can become difficult to control rather quickly because of the number of quotation marks and parentheses. If this proves difficult to follow for you, simply break the statement down by defining the argument for execute(), the actual MySQL statement, in a separate line. As with elsewhere in Python, you can use triple quotes to assign a value verbatim. The preceding call could then be rewritten as follows:

statement = """INSERT INTO menu(name, price) VALUES("shark", "13.00")"""
cur.execute(statement)

Using triple quotes is also helpful for handling more complex statements as they can bridge multiple lines. This makes it easier to format statements in a way that humans can read more easily. Therefore, to use the ON DUPLICATE KEY UPDATE... , we can define the statement:

INSERT INTO Combo(ID, Name, CountryCode) VALUES ("4078", "Singapore", "SGP") ON DUPLICATE KEY UPDATE ID=ID+1;


					  

As follows for better readability:

statement = """INSERT INTO Combo(ID, Name, CountryCode)
VALUES ("4078", "Singapore", "SGP")
ON DUPLICATE KEY UPDATE ID=ID+1;"""

As the Zen of Python reads:

Readability counts

The virtue of readability in programming is often couched in terms of being kind to the next developer who works on your code. There is more at stake, however. With readability comes not only maintainability but control.. If it takes you too much effort to understand the code you have written, you will have a harder time controlling the program's flow and this will result in unintended behavior. The natural consequence of unintended program behavior is the compromising of process stability and system security.


More complex INSERT commands

To pass the INSERT command with any of its optional arguments, simply include them in the statement. For example, where we had the following INSERT...SELECT... command:

INSERT INTO Combo(ID, Name, CountryCode) SELECT ID, Name, CountryCode FROM City WHERE ID < 1000;


					  

One can simply pack all of that into the value of statement:

statement = """INSERT INTO Combo(ID, Name, CountryCode) SELECT ID, Name, CountryCode FROM City WHERE ID < 1000;"""


					  

The DELAYED argument can be passed similarly. The previous statement passed through execute() would look like this:

cur.execute("""INSERT DELAYED INTO Combo(ID, Name, CountryCode) SELECT ID, Name, CountryCode FROM City WHERE ID < 1000;""")


					  

Likewise, we could include the INSERT...ON DUPLICATE KEY UPDATE... argument as follows:

cur.execute("""INSERT INTO Combo(ID, Name, CountryCode) VALUES ("4078", "Singapore", "SGP") ON DUPLICATE KEY UPDATE ID=ID+1""")


					  

It is not necessary to use triple quote marks when assigning the MySQL sentence to statement or when passing it to execute(). However, if you used only a single pair of either double or single quotes, it would be necessary to escape every similar quote mark. As a stylistic rule, it is typically best to switch to verbatim mode with the triple quote marks in order to ensure the readability of your code.

 
Others
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us