Louis Smith
Louis Smith

Reputation: 73

How to create and insert to database with shell scripting?

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?

Upvotes: 0

Views: 1720

Answers (2)

nickmarko
nickmarko

Reputation: 81

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

Upvotes: 0

Paul Schulte
Paul Schulte

Reputation: 11

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)

Upvotes: 1

Related Questions