Python operation MySQL, very convenient, using the MYSQLDB library, the basic operation is as follows:
Inquire:
1 Try:2conn = MySQLdb.connect (Host=self.ip, User=self.username,passwd=self.password, Db=self.dbname, port=self.port)3Cur =conn.cursor ()4 cur.execute (SQL)5rows =Cur.fetchall ()6data =rows7 exceptMysqldb.error, E:8 PrintStr (e)9 Print "connet MySQL db error ..."TenSys.exit ()
Insert data:
Try : = MySQLdb.connect (Host=self.ip, User=self.username, Passwd=self.password, Db=self.dbname, port=self.port) = conn.cursor () cur.execute (SQL, value) conn.commit () conn.close () cur.close () except Mysqldb.error, E: Print Str (e) Print " Execute MySQL db error ... " sys.exit ()
Use Utf-8 to solve the coding problem when using the process of coding:
Conn.set_character_set ('utf8') cur.execute ('set NAMES UTF8; ' ) Cur.execute ('set CHARACTER set UTF8; ' ) Cur.execute ('SET Character_set_connection=utf8; ')
And the problem with the backslash, MySQL by default, the backslash escaped, my workaround is to replace the backslash with a double backslash:
DataPath = Datapath.replace ('\ \'\\\\')
The MySQL statement needs to format the string, and the SQL string for the query needs to represent the variable placeholder with%, but Python seems to have to use%s
Executemany also supports multiple data insertions at the same time, but I'm not using this because it's easy to add loops outside.
Python Basics Summary-using MySQL