Saturday, October 15, 2016

Create a Database in MySQL

Now that I've got MySQL set up and running, it's time to use it. But when I try to connect I get an error because there is no database.

So to create a database I connect to the MySQL server:

[ed@localhost ~]$ mysql -u root -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 10.1.17-MariaDB MariaDB Server

Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database tempdb;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]>

Unfortunately, when I try to connect from Python, I still get this error:

   OperationalError: (1049, "Unknown database 'testdb'")

So I list the databases MySQL knows about:

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| tempdb             |
| test               |
+--------------------+
5 rows in set (0.07 sec)

The code I am using looks like this:

    # Open database connection
    db = MySQLdb.connect("localhost","root","xxx","testdb" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # execute SQL query using execute() method.
    cursor.execute("SELECT VERSION()")

    # Fetch a single row using fetchone() method.
    data = cursor.fetchone()

    print "Database version : %s " % data

    # disconnect from server
    db.close()    

OK, the problem was that the name I created was "tempdb" but the name I was using in Python code was "testdb". I changed it to tempdb, and now the code works!! ;-)


No comments:

Post a Comment