Python operation mysql (2) Database connection and cursor establishment
# _ * _ coding:utf-8_*_import MySQLdbDBHOST = "192.168.89.101" DBUSER = "root" DBPASSWD = "1qaz#EDC" DB = "soms" PORT = 3306CHARSET = "utf8" # establish a connection to the database conn = MySQLdb.connect (host=DBHOST, user=DBUSER, passwd=DBPASSWD, db=DB, port=PORT, charset=CHARSET) cur = conn.cursor () # create cursors, Python executes SQL statements through cursors
Common methods for cursor objects:
Name
Describes close () closing cursors. After that, the cursor cannot use execute (query [, args]) to execute a SQL statement, which can take the parameter executemany (query, pseq) to execute the sql statement fetchone () on each parameter in the sequence pseq. Fetchone () returns a query result fetchall () returns all query results fetchmany ([size]) returns size result nextset () moves to the next result scroll (value,mode='relative') moves the cursor to the specified row If mode='relative', means to move the value bar from the current row, if mode='absolute', means to move the value bar from the first row of the result set. Cur = conn.cursor () # to establish a cursor Python executes the SQL statement through the cursor # inserts a record cur.execute ("insert into discovery (ip,port,status) values (% s ip,port,status% s)", ('192.168.89.23)) # data is submitted to conn.commit ()
Check the database:
Mysql > select * from discovery
+-- +
| | id | ip | port | status | |
+-- +
| | 1 | 192.168.89.3 | 22 | True |
| | 3 | 192.168.89.23 | 22 | True |
+-- +
2 rows in set
The same is true of query operations, which can be done by analogy.