0

I am trying to write a shell script that will create a database. In a different script I want to execute some Linux commands and then insert the output to the database. I have an idea how to do it but is it possible to do it with python? Which is easier?

2 Answers 2

1

Creating a simple database in python is fairly easy:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

Then you can create a table, for example:

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

And finally insert into the new table:

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)

mydb.commit()

(compare https://www.w3schools.com/python/python_mysql_create_db.asp)

Sign up to request clarification or add additional context in comments.

Comments

0

It's much easier in shell.

Creating database:

$ command="CREATE DATABASE IF NOT EXISTS test_db;"
$ mysql -uroot -p<PASSWORD_HERE> <<< $command

Confirm:

$ mysql -uroot -p<PASSWORD_HERE> <<< "show databases;"
Database
information_schema
mysql
performance_schema
phpmyadmin
test_db

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.