在本教程的这一部分中,无涯教程将讨论将python应用程序连接到数据库的步骤。
有以下步骤将python应用程序连接到数据库。
为了在MySQL数据库和python应用程序之间创建连接,使用mysql.connector模块的connect()方法。
在方法调用中传递数据库详细信息,例如HostName,用户名和数据库密码。该方法返回连接对象。
下面给出了使用connect()的语法。
Connection-Object= mysql.connector.connect(host = <host-name> , user = <username> , passwd = <password> )
考虑以下示例。
import mysql.connector #创建连接对象 myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "Learnfk") #打印连接对象 print(myconn)
输出:
<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>
在这里,必须注意,如果要连接到特定数据库,可以在connect()方法中指定数据库名称。
import mysql.connector #创建连接对象 myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "Learnfk", database = "mydb") #打印连接对象 print(myconn)
输出:
<mysql.connector.connection.MySQLConnection object at 0x7ff64aa3d7b8>
游标对象可以定义为Python DB-API 2.0中指定的抽象。通过与数据库的相同连接,它使能够拥有多个单独的工作环境。可以通过调用连接对象的" cursor"函数来创建光标对象。游标对象是对数据库执行查询的重要方面。
下面给出了创建游标对象的语法。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-mysql-database-connection.html
来源:LearnFk无涯教程网
<my_cur> = conn.cursor()
import mysql.connector #创建连接对象 myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "Learnfk", database = "mydb") #打印连接对象 print(myconn) #创建光标对象 cur = myconn.cursor() print(cur)
输出:
<mysql.connector.connection.MySQLConnection object at 0x7faa17a15748> MySQLCursor: (Nothing executed yet)
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)