python -m pip install mysql-connector
2、使用
数据库连接
需要导入驱动模块,mysql.connector,并使用connector模块中的connect方法连接数据库,
查看源码 def connect(*args, **kwargs),该方法中允许传入元祖模式参数,和字典类型参数,
即就是:
#字典
localdb=mysql.connector.connect(
host='127.0.0.1',
user='root11',
passwd='root22')#元祖
localdb=mysql.connector.connect('127.0.0.1','root11','root22)
例一
importmysql.connector
localdb=mysql.connector.connect(
host='127.0.0.1',
user='root11',
passwd='root22')print(localdb)
mycursor=localdb.cursor()
mycursor.execute("CREATE DATABASE python3sql")
mycursor.execute("show databases")for x inmycursor:print(x)
数据库操作
正如例一,创建一个cursor实例来执行数据库操作。
插入:在执行插入语句时候,数据库表有更新,需要像数据库提交事务,
mydb.commit() # 数据表内容有更新,必须使用到该语句
此处插入可以进行多数据插入,使用 mycursor.executemany(sql,val2) 方法。
删除:同插入
更新:同插入
查询:在执行查询语句时候,需要返回查询结果,
全部返回 fetchall(self),
部分返回 fetchmany(self,size=1),
单数据返回 fetchone(self)
---------------------
作者:IT_xiaocai27
来源:CSDN
原文:https://blog.csdn.net/weixin_38328865/article/details/84983282
版权声明:本文为博主原创文章,转载请附上博文链接!
以上是我看到一个博主写的 我觉得易懂
1.使用connect()构造函数
importmysql.connector
cnx= mysql.connector.connect(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
使用connection.MySQLConnection() 类创建连接对象
from mysql.connector import(connection)
cnx= connection.MySQLConnection(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
在字典中定义连接参数并使用 **运算符
importmysql.connector
config={'user': 'scott','password': 'password','host': '127.0.0.1','database': 'employees','raise_on_warnings': True
}
cnx= mysql.connector.connect(**config)
cnx.close()
处理链接错误使用try语句并使用error.Error异常捕获所有错误
importmysql.connectorfrom mysql.connector importerrorcodetry:
cnx= mysql.connector.connect(user='scott',
database='employ')exceptmysql.connector.Error as err:if err.errno ==errorcode.ER_ACCESS_DENIED_ERROR:print("Something is wrong with your user name or password")elif err.errno ==errorcode.ER_BAD_DB_ERROR:print("Database does not exist")else:print(err)else:
cnx.close()
2.使用Connector / Python查询数据
importdatetimeimportmysql.connector
cnx= mysql.connector.connect(user='scott', database='employees')
cursor=cnx.cursor()
query= ("SELECT first_name, last_name, hire_date FROM employees"
"WHERE hire_date BETWEEN %s AND %s")
hire_start= datetime.date(1999, 1, 1)
hire_end= datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))for (first_name, last_name, hire_date) incursor:print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()