Create MySQLdb database using Python script - python

I'm having troubles with creating a database and tables. The database needs to be created within a Python script.
#connect method has 4 parameters:
#localhost (where mysql db is located),
#database user name,
#account password,
#database name
db1 = MS.connect(host="localhost",user="root",passwd="****",db="test")
returns
_mysql_exceptions.OperationalError: (1049, "Unknown database 'test'")
So clearly, the db1 needs to be created first, but how? I've tried CREATE before the connect() statement but get errors.
Once the database is created, how do I create tables?
Thanks,
Tom
Here is the syntax, this works, at least the first time around. The second time naturally returns that the db already exists. Now to figure out how to use the drop command properly.
db = MS.connect(host="localhost",user="root",passwd="****")
db1 = db.cursor()
db1.execute('CREATE DATABASE test1')
So this works great the first time through. The second time through provides a warning "db already exists". How to deal with this? The following is how I think it should work, but doesn't. OR should it be an if statement, looking for if it already exists, do not populate?
import warnings
warnings.filterwarnings("ignore", "test1")

Use CREATE DATABASE to create the database:
db1 = MS.connect(host="localhost",user="root",passwd="****")
cursor = db1.cursor()
sql = 'CREATE DATABASE mydata'
cursor.execute(sql)
Use CREATE TABLE to create the table:
sql = '''CREATE TABLE foo (
bar VARCHAR(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
'''
cursor.execute(sql)
There are a lot of options when creating a table. If you are not sure what the right SQL should be, it may help to use a graphical tool like phpmyadmin to create a table, and then use SHOW CREATE TABLE to discover what SQL is needed to create it:
mysql> show create table foo \G
*************************** 1. row ***************************
Table: foo
Create Table: CREATE TABLE `foo` (
`bar` varchar(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
phpmyadmin can also show you what SQL it used to perform all sorts of operations. This can be a convenient way to learn some basic SQL.
Once you've experimented with this, then you can write the SQL in Python.

I think the solution is a lot easier, use "if not":
sql = "CREATE DATABASE IF NOT EXISTS test1"
db1.execute(sql)

import MySQLdb
# Open database connection ( If database is not created don't give dbname)
db = MySQLdb.connect("localhost","yourusername","yourpassword","yourdbname" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# For creating create db
# Below line is hide your warning
cursor.execute("SET sql_notes = 0; ")
# create db here....
cursor.execute("create database IF NOT EXISTS yourdbname")
# create table
cursor.execute("SET sql_notes = 0; ")
cursor.execute("create table IF NOT EXISTS test (email varchar(70),pwd varchar(20));")
cursor.execute("SET sql_notes = 1; ")
#insert data
cursor.execute("insert into test (email,pwd) values('test#gmail.com','test')")
# Commit your changes in the database
db.commit()
# disconnect from server
db.close()
#OUTPUT
mysql> select * from test;
+-----------------+--------+
| email | pwd |
+-----------------+--------+
| test#gmail.com | test |
+-----------------+--------+

Related

Insert into with condition

I'm working with python and using pymysql library and i want to write a query that insert an array in a line where a column has some special value.
For example insert 'hi' into a column where user_id is 22
for that query i write this code
from pymysql import *
chat_id = 22
user_first_name = "hi"
db = connect(host="localhost", port=3306, user="root", passwd="",
db='support',charset='utf8')
cursor = db.cursor()
cursor.execute("""INSERT INTO users user_firstname VALUE %s WHERE user_id is
%s""",(user_first_name, chat_id))
db.commit()
how should i write this query in correct form?
If I'm undertanding, correctly, rather than an INSERT INTO, it seems you need an UPDATE:
cursor.execute("""UPDATE users SET user_firstname='%s' WHERE user_id=%s""",(user_first_name, chat_id))
Francisco is right though. If you have a user_id already, then an UPDATE should be used to change the value of and existing record. The INSERT command, creates a new record.

SQLite-Manager on Firefox and Python

I have written a small test application using SQLite with Python 3.3:
import sqlite3
MDB = sqlite3.connect('D:\MDB.db') # create the db object
cursor = MDB.cursor() # assign a cursor
cursor.execute('''CREATE TABLE IF NOT EXISTS section (
Code INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Description TEXT )
''')
cursor.execute('''DELETE FROM section''') # delete contents for reruns
cursor.execute('''INSERT INTO section
(Description)
VALUES (?)
''', ('Abdul, Paula',))
cursor.execute('''INSERT INTO section
(Description)
VALUES (?)
''', ('ABWH',))
print('Results:\n')
cursor.execute('''SELECT * FROM section''')
selection = cursor.fetchall()
for row in selection:
print('\t', row)
The SELECT statement shows the results expected (seeming to indicate that the row exists), but if I connect to the database with SQLite-Manager, the table exists but is empty, and if I try the same query with another script connected to the database, nothing is returned. Can anyone please explain what I am doing wrong?
You're not saving changes (calling MDB.commit).

SQL connector using Python

I have a SQL database which I wish to run a query on through python. I have the following code:
sql='select * from mf where frequency=220258.0;'
cur.execute(sql)
Where I use the same select command in sqlite3 directly it works, but through Python no database entries are outputted.
What am I doing wrong?
Consider this SQLite database.
$ sqlite3 so.sqlite3 .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE t (f1 integer, f2 text);
INSERT INTO "t" VALUES(1,'foo');
INSERT INTO "t" VALUES(2,'bar');
INSERT INTO "t" VALUES(3,'baz');
COMMIT;
Python connects and queries this database like this.
import sqlite3
con = sqlite3.connect("so.sqlite3")
cur = con.cursor()
cur.execute("select * from t where f1 = 2")
print(cur.fetchone())
Output:
(2, 'bar')
You have to use one of cur.fetchone(), cur.fetchall(), or cur.fetchmany() to get rows from the cursor. Just doing cur.execute() does not return the rows.

sqlite3 python ATTACH DATABASE copy table .schema

System
Python 2.7
SQLite3
Code
I want to restore a backup of a database by copying a table from the _bak.db to the being used .db.
conn = sqlite3.connect(os.path.join("data", "db", "Kanji-story.db"))
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS current")
c.execute("ATTACH DATABASE ? AS db2", (os.path.join('data', 'db', 'Kanji-story_bak.db'),))
# TODO Code for Creating table with the same structure
c.execute("INSERT INTO main.current SELECT * FROM db2.current")
Question
To execute the last statement I first have to create a table in Kanji-story.db with the same structure as Kanji-story_bak.db (see # TODO). How do I create a TABLE with the same structure? I know there is .schema command in SQLite3, but how do I effectively use that command to make a new table?
Inspired by the answer of #CL. , the full code is:
conn = sqlite3.connect(os.path.join("data", "db", "Kanji-story.db"))
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS current")
c.execute("ATTACH DATABASE ? AS db2", (os.path.join('data', 'db', 'Kanji-story_bak.db'),))
c.execute("SELECT sql FROM db2.sqlite_master WHERE type='table' AND name='current'")
c.execute(c.fetchone()[0]) # Contains: CREATE TABLE current (framenum INTEGER, nextKanji INTEGER)
c.execute("INSERT INTO main.current SELECT * FROM db2.current")
conn.commit()
conn.close()
SQLite has no mechanism to execute indirect commands.
To get the original table definition, you have run the same query used internally by .schema:
SELECT sql FROM db2.sqlite_master WHERE type='table' AND name='current'
My sqlite3 version 3.18.0 has create table main.current as select * from db2.current

Python with SQLite3: select does not display any data

I am writing a very simply database using python and sqlite3. And when I created a table and some data I wanted to display this data using (in terminal) command "Select * From Data", but no data appears, although I checked using other methods that the data is inserted to the table.
How I create my table and data:
db = connect('database.db')
db_cursor = db.cursor()
db_cursor.execute("CREATE TABLE IF NOT EXISTS Data(Id INT, Name TEXT, City TEXT)")
db_cursor.execute("INSERT INTO Data VALUES (1, 'ABC', 'XYZ')")
If I do:
db_cursor.execute("Select * From Data")
print self.db_cursor.fetchall()
the data is displayed.
But when I run a command line and try to do:
sqlite3 database.db
sqlite> .mode column
sqlite> .headers on
sqlite> SELECT * FROM Data;
no data appears. I checked using
sqlite> .tables
that table is generated correctly.
Why sqlite3 run from command line does not display data?
You need to commit your transaction before it is permanently part of the database:
db.commit()
You can use the database connection as a context manager to commit automatically if a block of code executed successfully:
with db:
db_cursor = db.cursor()
db_cursor.execute("INSERT INTO Data VALUES (1, 'ABC', 'XYZ')")
Note that DDL statements (creating tables and other data definitions) are automatically committed, which is why you saw the table in the database, but not the new row.

Categories

Resources