Some ways to call MySQL with Python are summarized:
1. Code statement:
# Encoding:utf-8
#!/usr/bin/python
At the beginning of the declaration, to avoid the input in Chinese, prompt declaration error (of course, the input Chinese garbled situation, need to be resolved separately)
2. When calling, be aware that host = ' localhost ', there is a need to note, sometimes with their own server ' 120.24.85.37 ', but will appear _mysql_operation_error (2013 ...) Such errors can be tried with ' localhost '/' 127.0.0.0 ' to solve, but in which case with localhost, what situation with their own server, need to be clearer later.
3.python call MySQL requires MYSQLDB package, installation method according to other third-party package installation can
4.python call MySQL Common Operations Command:
Import MySQLdb
conn = MySQLdb.connect (
Host = ' Lacalhost ',
Port = 22, here is the location of the ports, the data type is integral type, no quotation marks are required
User= ',
Passwd= ', here is the user name and password for the database
db = ")
cur = conn.cursor ()
Cur.execute ("CREATE TABLE student (ID int,name char (), Class char ())") ==> Create data table
Cur.execute ("INSERT INTO student Values" ("2", "Tom", "3year 2class") ==> Insert a value
Insert Optimization:
sql = "INSERT into student values (%s,%s,%s)"
Insert 1 data: Cur.execute (SQL, ("2", "Tom", "3year 2class"))
Insert multiple data: Cur.executemany (sql,[("2", "Tom", "3year2class"),
("3", "Lily", "3year2class")])
Cur.execute ("update student Set class = ' 3year 1class ' WHERE name = ' Tom '") ==> modify data based on conditions
Cur.execute ("Delete from student where class = ' 3year 2class '") ==> Delete qualifying data
Sql= "SELECT * FROM Student"
Cur.execute (SQL)
info = Cur.fetchall () ==> get all the information in the table
For row in info:
Print row
==> print out all the elements in the table
Cur.close () ==> close cursor
Conn.commit () ==> commits the transaction and is not required when inserting to the database
Conn.close () ==> close connection
MySQL Initial 2