How to connect Database in PythonThe database is a well-organized collection of structured information or data stored in a computer system. In database, the data is arranged in the tabular form, and we can access that information or data by querying. Python can be used to connect the Database. MySQL is one of the most popular Databases. In this tutorial, we will learn to establish a connection to MySQL via Python. Let’s understand the following steps to work with the MySQL using Python.
Install MySQL DriverFirst, we need a MySQL driver in our system. Install the MySQL software and configure the settings. We will use the MySQL connector driver, which is installed using the pip command. Open a command prompt and type the following command. Press the enter button. It will download the MySQL driver.
Let’s check whether we have installed it properly or not. It can be done by importing the mysql.connector. If this line is executed without error, it means MySQL connector has installed properly. We are ready to use it. Create a Connection ObjectThe mysql.connector provides the connect() method used to create a connection between the MySQL database and the Python application. The syntax is given below. Syntax: The connect() function accepts the following arguments.
Consider the following example. Example – Output: <mysql.connector.connection.MySQLConnection object at 0x7fb142edd780> Create a Cursor ObjectThe connection object is necessary to create because it provides the multiple working environments the same connection to the database. The cursor() function is used to create the cursor object. It is import for executing the SQL queries. The syntax is given below. Syntax: Let’s understand the following example. Example – Output:
Executes the QueryIn the following example, we will create a database by executing the query. Let’s understand the following example. Example – Output: 'information_schema',) ('javatpoint',) ('javatpoint1',) (New_Pythondb) ('mydb',) ('mydb1',) ('mysql',) ('performance_schema',) ('testDB',) In the above tutorial, we have discussed how we can establish a connection to MySQL via Python. You can learn complete Python with MySQL from (https://www.javatpoint.com/python-mysql-database-connection). |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263613.html