Connect Python to mysql, and connect python to mysql
If you don't talk much about it, go directly to the Code:
#! /Usr/bin/python # coding: utf-8import MySQLdb # establish a connection with the mysql database con = MySQLdb. connect (host = "127.0.0.1", port = 3306, user = "root", passwd = "000000") # obtain the cursor = export cute ("create table mm (id int, name varchar (20) ") # insert a record value = (1," user "into cursor.exe cute (" insert into mm values (% s, % s) ", valuenames repeated cursor.exe cute (" insert into mm values (1, 'user') ") # insert multiple records values = [(2," user2 "), (3, "user3" inserting into cursor.exe cute.pdf ("insert into mm values (% s, % s)", values?#cursor.exe cute ("insert into mm values (2, 'zuser'), (3, 'wuser') ") # query SQL =" select * from mm "res = cursor.exe cute (SQL) # obtain a record # info = cursor. fetchone () # retrieve multi-hop data infoo = cursor. fetchmany (res) # print the table data for line in infoo: print line # submit con. commit () # Close the cursor. close () # close the connection con. close ()
Note:
Con. commit () is required for delete and update, while select and insert () can be successful without commit.