一、怎么配置mysqlclient
mysqlclient是Python环境下用来连接MySQL数据库的模块,它是利用C API进行编写的。下面介绍如何配置mysqlclient:
1、安装MySQL数据库:
sudo apt-get install mysql-server
2、安装mysqlclient:
pip install mysqlclient
3、测试连接:
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
print(result)
cursor.close()
conn.close()
二、client
mysqlclient可以通过Connection类来连接数据库实现增删改查等操作。
1、创建连接:
import MySQLdb
conn = MySQLdb.connect(user="root", passwd="", db="test", host="localhost")
2、创建游标:
cursor = conn.cursor()
3、执行SQL语句:
cursor.execute("CREATE TABLE student(id INT, name VARCHAR(20));")
cursor.execute("INSERT INTO student VALUES (1, 'Alice');")
4、提交修改:
conn.commit()
5、释放资源:
cursor.close()
conn.close()
三、Windows mysql安装教程
为了在Windows环境下进行mysqlclient的开发,需要先安装MySQL数据库:
1、下载安装程序:
https://dev.mysql.com/downloads/mysql/
2、安装MySQL:
(1)按照提示一步步安装,注意选择需要的组件。(2)设置root用户的密码。
3、配置MySQL环境变量:
(1)把mysql安装目录下的bin目录的路径添加到PATH环境变量中。(2) 然后重新打开一个cmd窗口,输入mysql,如果出现mysql提示符说明配置成功。
四、 mysqlclient的使用示例
1、查询数据:
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM student")
result = cursor.fetchall()
for record in result:
print("id: %d, name: %s" % (record[0], record[1]))
cursor.close()
conn.close()
2、插入数据:
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
cursor = conn.cursor()
cursor.execute("INSERT INTO student VALUES (2, 'Bob')")
conn.commit()
cursor.close()
conn.close()
3、更新数据:
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
cursor = conn.cursor()
cursor.execute("UPDATE student SET name=%s WHERE id=%s", ("Tom", 1))
conn.commit()
cursor.close()
conn.close()
4、删除数据:
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
cursor = conn.cursor()
cursor.execute("DELETE FROM student WHERE id=%s", (2,))
conn.commit()
cursor.close()
conn.close()