Wednesday, February 6, 2019

Database Programming using Python

I finally decided to go back to blogging to at least maximize the payment I made on the domain name and help out my students in their Python coding.

So, I have to start it by writing some codes to enable insertion of a record to a database I have made using XAMPP SQL.

For the sample database I created, see below:

You have to create this database and the tables before you create your front-end code using Python. Make sure though that you install the needed database connector for your OS and Python version. In my case, I'm using Python 3.4 using Windows 10.

Now for us to insert a record, you can try the Python code below.

Now the username and password of your database is dependent on whether you have set this during SQL installation.  If none, then leave these parameters blank.  I have used SCHOOL for my database

Dont forget that we have installed the db connector earlier, so, to connect our Python with XAMPP sql, then we need IMPORT MYSQL.CONNECTOR.

CURSOR( ) is used to allow Python  to execute SQL commands during database session. With this we can insert, select, update, delete records with our database

Now, dont forget your SQL to insert into the needed field names. If you forgot this, go back to your XAMPP and check your table structure to see the field names and their data types.

The INSERT record program above allows you dynamic session. So, you can prompt your user for any input and with these inputs, we store them to our database.

I have called this function using a menu. Once, you have created all other operations like VIEW, UPDATE, DELETE, then, we can all call them using our menu interface.

To see if your code is working, run it and make sure that you shift to your XAMPP to see if the new record is added. See below:

Now, it's your turn!

No comments: