Use Python to operate MySQL Databases and pythonmysql Databases
1. Install mysql-python
Run the following command:
Pip intall mysql-python
After installation:
Import MySQLdb
If no error occurs, the installation is successful.
2. Connect to MySQL
Db = MySQLdb. connect ("localhost", "root", "1", "fs ")
Specifically, localhost is the server name, root is the user name, 1 is the password, and fs is the database name, provided that the MySQL database has set the corresponding user name and password.
After the connection is successful
Cur = db. cursor ()
Obtain the cursor.
3. query data
Cur.exe cute ("select * from TableName where A = % s and B = % s order by C desc", (a, B) results = cur. fetchall () result = list (results)
Cur.exe cute () executes the query statement. cur. fetchal () gets the result set and converts the result set to a tuple Array Using list (). The rest is easy to process.
4. Write Data
Cur.exe cute ("insert into A values (% s, % s)", (x1, x2, x3, x4) db. commit ()
Regardless of the type of the written field in the table, % s is used. Otherwise, an error occurs. After writing, commit () is required ().
The other operations include the deleteand updateoperations, both of which are temporary. You can use cur.exe cute () to execute the SQL statement and use % s to substitute the parameter.