I have installed mysql for python and running python from command line. I am getting syntax error while creating a database.
>>> import MySQLdb
>>> CREATE DATABASE chom;
File "<stdin>", line 1
CREATE DATABASE chom;
^
SyntaxError: invalid syntax
CREATE DATABASE chom; this should be run from the MySQL command line client, not from the Python shell.
So, first type mysql -u yourusername -p from your command line. It will ask you for a password, type it in. Then you will get a prompt like this mysql>. Here is where you would type that query.
Now, if you want to do this through Python, you can, but it will require some more work.
>>> import MySQLdb as db
>>> con = db.connect(user="foo", passwd="secret")
>>> cur = con.cursor()
>>> cur.execute('CREATE DATABASE chom;')
See this guide for some examples on how to work with Python and MySQL using the standard DB API.
If you want create a database,you can try:
import MySQLdb
db1 = MySQLdb.connect(host="localhost",user="root",passwd="****")
cursor = db1.cursor()
sql = 'CREATE DATABASE chom'
cursor.execute(sql)
Related
I understand how to open a database using a python script:
import sqlite3 as lite
.
.
con = lite.connect(db_name)
However what I have is a lot of database files made with tsk_loaddb, when I am in sqlite3 I can use the following
SQLite version 3.8.7.2 2014-11-18 20:57:56
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open /work/jmjohnso1/db_project/db_IN60-1020
sqlite> .tables
blackboard_artifact_types tsk_files_derived_method
blackboard_artifacts tsk_files_path
blackboard_attribute_types tsk_fs_info
blackboard_attributes tsk_image_info
tsk_db_info tsk_image_names
tsk_file_layout tsk_objects
tsk_files tsk_vs_info
tsk_files_derived tsk_vs_parts
However, I am not understanding how to do it in python. My question is how do I translate the open command with the sqlite3 python library.
Turns out I had a newline in the name because I was reading from a file. So the following works.
def open_sql(db_folder, db_name, table):
# databases are located at /work/jmjohnso1/db_project
path_name = os.path.join(db_folder,db_name).strip()
con = lite.connect(path_name)
cur = con.cursor()
cur.execute('SELECT * FROM ' + table)
col_names = [cn[0] for cn in cur.description]
rows = cur.fetchall()
print_header(col_names)
print_output(rows)
con.close()
The end goal is to modify Firefox cookies.sqlite db before starting Firefox.
At present, I want to display what tables are in the db. I copied the cookies.sqlite db to my desktop. I'm working with the db on my desktop.
This is my first time using sqlite. I copied some code, but I'm not able to read what tables are in the db.
List of tables, db schema, dump etc using the Python sqlite3 API
Here is what I get in the terminal. I see the listing of the tables.
me $ ls cookies.sqlite
cookies.sqlite
me $ sqlite3 cookies.sqlite
SQLite version 3.8.10.2 2015-05-20 18:17:19
Enter ".help" for usage hints.
sqlite> .tables
moz_cookies
sqlite> .exit
me $ # I run my python script
me $ ./sqlTutorial.bash
SQLite version: 3.8.10.2
table records...
[]
more table records...
me $ cat dump.sql
BEGIN TRANSACTION;
COMMIT;
me $
python code. All I want to do is display the tables in the cookie.sqlite db.
#! /bin/python
import sqlite3 as lite
import sys
con = lite.connect('cookie.sqlite')
with con:
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print ("SQLite version: %s" % data)
print ("table records...")
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
print ("more table records...")
with open('dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
As you noticed, the database name is cookies.sqlite not cookie.sqlite.
Why didn't I get an error? I though python would error out on. con = lite.connect('cookie.sqlite')
Connecting to a sqlite database either opens an existing database file, or creates a new one if the database didn't exist.
I am new at SQLite in Python and I am trying to create a database connection.
I have the following as a datbase location:
E:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\master.mdf (i think)
The database is called FTHeader. However, when I try it i get an error saying unable to open database file
any help would be greatly appreciated.
Pick your poison from here and import the module as db and the following should sort you, cribbing from PEP 249:
import adodbapi as db
import adodbapi.ado_consts as db.consts
Cfg={‘server’:’192.168.29.86\\eclexpress’,‘password’:‘xxxx’,‘db’:‘pscitemp’}
constr = r”Provider=SQLOLEDB.1; Initial Catalog=%s; Data Source=%s; user ID=%s; Password=%s; “ \
% (Cfg['db'], Cfg['server'], ‘sa’, Cfg['password'])
conn=db.connect(constr)
You should now be connected to your database after replacing the Cfg dictionary to match your installation.
I have created a database when completing a controlled assesment, here is the code that I have used:
import sqlite3
new_db = sqlite3.connect ('R:\\subjects\\Computing & ICT\\Student Area\\Y11\\Emilyc\\results1.db')
c=new_db.cursor()
c.execute('''CREATE TABLE results1
(
results1_name text,
results1_class number,
quiz_score number)
''')
#Class 1
c.execute('''INSERT INTO results1
VALUES ('John Watson','1','5')''')
It's - for sqlplus - commands:
SQL> set serveroutput on
SQL> exec where.my_package.ger_result('something');
something=1823655138
And it's - for cx_Oracle:
>>> c.callproc('where.my_package.ger_result', ('something',))
['something']
As You can see - the results are different.
I have no idea, how to fix it. :[
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('my_ip_address_server_next_port', 0000, 'sid')
db = cx_Oracle.connect('user', 'password', dsn_tns)
curs = db.cursor()
curs.callproc("dbms_output.enable")
curs.callproc('where.my_package.ger_result', ['something',])
statusVar = curs.var(cx_Oracle.NUMBER)
lineVar = curs.var(cx_Oracle.STRING)
while True:
curs.callproc("dbms_output.get_line", (lineVar, statusVar))
if statusVar.getvalue() != 0:
break
print lineVar.getvalue()
Sorry, I can't reproduce this one.
I don't have your PL/SQL package, so I used the following stored procedure instead:
CREATE OR REPLACE PROCEDURE p_do_somet (
p_param IN VARCHAR2
) AS
BEGIN
dbms_output.put_line(p_param || '=1823655138');
END;
/
I got the same output, something=1823655138, from SQL*Plus and from using the Python script in your answer.
If you're getting different results using SQL*Plus and cx_Oracle, then either your stored procedure is doing something very funny (I don't know what could cause it to do this), or your SQL*Plus session and Python script are not connecting to the same database and/or schema.
How can you fix the SQL-statement in Python?
The db connection works. However, cur.execute returns none which is false.
My code
import os, pg, sys, re, psycopg2
try:
conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'")
except: print "unable to connect to db"
cur = conn.cursor()
print cur.execute("SELECT * FROM courses") # problem here
The SQL-command in Psql returns me the correct output.
I can similarly run INSERT in Psql, but not by Python's scripts.
I get no warning/error to /var/log.
Possible bugs are
cursor(), seems to be right however
the syntax of the method connect(), seems to be ok however
You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.
You should probably have a read through the a tutorial for DB-API.
You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.