sqlite3 in data receive python communication - python

this is a simple chat code in python programming.I want to receive an increasingly aware of and store the ip, host, and message. But as it is, it only records once and not always? resolve like this?
(I use SQLITE3)
while true:
data = conn.recv (1024)
cur=con.cursor()
cur.execute("CREATE TABLE amo(IP INT, data TEXT)")
cur.execute("INSERT INTO amo VALUES(?,?)", (HOST, data))

Duarte, you have very nearly answered your own question, you are re-creating the table with each loop. Separate out your logic:
# establish you database connection and create the table, if it does not already exist
... (create your db connection here) ...
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS amo(IP INT, data TEXT)")
# open your chat connection, and store the data
while True:
... (chat data) ...
cur.execute("INSERT INTO amo({},{})".format(HOST, data))
You will only have to create the table once, then it will be in the sqlite3 db, you can establish a connection to the db at the start of our script, and manipulate the data in the db to your heart's content after that.

Related

How to test Cloud Function in GCP where I am inserting data into Database

I am trying to test this function which inserts data into postgres via GCP Cloud Function. I am having trouble testing this. It say some JSON is required. However what is exactly required her to be called?
def hello_world(self):
# establishing the connection
conn = psycopg2.connect(
database='somedb',
user='someuser',
password='somepwd',
host='XX.XXX.XXX.XXX',
port='5432'
)
# creating a cursor object
cursor = conn.cursor()
# list that contain records to be inserted into table
data = [('Babita', 'Bihar'), ('Anushka', 'Hyderabad'),
('Anamika', 'Banglore'), ('Sanaya', 'Pune'),
('Radha', 'Chandigarh')]
# inserting record into employee table
for d in data:
cursor.execute("INSERT into employee(name, state) VALUES (%s, %s)", d)
# print("List has been inserted to employee table successfully...")
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()

How can I sort a database by date?

I am creating a Python app that will store my homework in a database (using PhpMyAdmin). Here comes my problem:
At this moment, I am sorting every input with an ID (1, 2, 3, 4...), a date (23/06/2018...), and a task (read one chapter of a book). Now I would like to sort them by the date because when I want to read what do I have to do. I would prefer to see what shall I do first, depending on when should I get it done. For example:
If I have two tasks: one 25/07/2018 and the other 11/07/2018, I would like to show the 11/07/2018 first, no matter if it was addead later than the 25/07/2018. I am using Python (3.6), pymysql and PhpMyAdmin to manage the database.
I have had an idea to get this working, maybe I could run a Python script every 2 hours, that sorts all the elements in the database, but I have no clue about how can I do it.
Now, I will show you the code that enters the values into a database and then it shows them all.
def dba():
connection = pymysql.connect(host='localhost',
user='root',
password='Adminhost123..',
db='deuresc',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `deures` (`data`, `tasca`) VALUES (%s, %s)"
cursor.execute(sql, (data, tasca))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `deures` WHERE `data`=%s"
cursor.execute(sql, (data,))
resultat = cursor.fetchone()
print('Has introduït: ' + str(resultat))
finally:
connection.close()
def dbb():
connection = pymysql.connect(host='localhost',
user='root',
password='Adminhost123..',
db='deuresc',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM `deures`"
cursor.execute(sql)
resultat = cursor.fetchall()
for i in resultat:
print(i)
finally:
connection.close()
Can someone help?
You don't sort the database. You sort the results of the query when you ask for data. So in your dbb function you should do:
SELECT * FROM `deures` ORDER BY `data`
assuming that data is the field with the date.

inserting a file to ms sql server through python

I am quite new to programming. I have written the following code by researching from StackOverflow and other sites. I am trying to upload a csv file to the MS SQL Server. Every time I run this it connects and then a message pops up 'Previous SQL was not a query'. I am not sure how to actually tackle this. Any suggestions and help will be appreciated
import pyodbc import _csv
source_path= r'C:\Users\user\Documents\QA Canvas\module2\Module 2 Challenge\UFO_Merged.csv'
source_expand= open(source_path, 'r')
details= source_expand.readlines
print('Connecting...')
try:
conn = pyodbc.connect(r'DRIVER={ODBC Driver 13 for SQL Server};'r'SERVER=FAHIM\SQLEXPRESS;'r'DATABASE=Ash;'r'Trusted_Connection=yes')
print('Connected')
cur = conn.cursor()
print('Cursor established')
sqlquery ="""
IF EXISTS
(
SELECT TABLE_NAME ,TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'UFO_MERGED' AND TABLE_SCHEMA = 'dbo')
BEGIN
DROP TABLE [dbo].[UFO_MERGED]
END
CREATE TABLE [dbo].[UFO_MERGED]
( [ID] smallint
,[COMMENTS] varchar(max)
,[FIRST OCCURANCE] datetime
,[CITY] varchar(60)
,[COUNTRY] varchar(20)
,[SHAPE] varchar(20)
,[SPEED] smallint
,[SECOND OCCURANCE] datetime
PRIMARY KEY(id)
) ON [PRIMARY]
"""
result = cur.execute(sqlquery).fetchall()
for row in result:
print(row)
print("{} rows returned".format(len(result)))
sqlstr= """
Insert into [dbo].[UFO_Merged] values ('()','()','()','()','()','()','()','()')
"""
for row in details[1:]:
row_data =row.split(',')
sqlquery=sqlstr.format(row_data[0],row_data[1],row_data[2],row_data[3],row_data[4],row_data[5],row_data[6],row_data[7])
result=cur.execute(sqlquery)
conn.commit()
conn.close()
except Exception as inst:
if inst.args[0]== '08001':
print("Cannot connect to the server")
elif inst.args[0] == '28000':
print("Login failed - check connection string")
else:
print(inst)
Well, make sure the SQL works first, before you try to introduce other technologies (Python, R, C#, etc.) on top of it. The SQL looks a little funky, but I'm not a SQL expert, so I can't say for sure, and I don't have time to recreate your setup on my machine. Maybe you can try with something a bit less complex, get that working, and then graduate to something more advanced. Does the following work for you?
import pyodbc
user='sa'
password='PC#1234'
database='climate'
port='1433'
TDS_Version='8.0'
server='192.168.1.103'
driver='FreeTDS'
con_string='UID=%s;PWD=%s;DATABASE=%s;PORT=%s;TDS=%s;SERVER=%s;driver=%s' % (user,password, database,port,TDS_Version,server,driver)
cnxn=pyodbc.connect(con_string)
cursor=cnxn.cursor()
cursor.execute("INSERT INTO mytable(name,address) VALUES (?,?)",('thavasi','mumbai'))
cnxn.commit()

Deleting a database file in :memory:

Background and Question
We are using :memory: to store our database when we are testing and would like to remove this before each test case run so that we will start from the beginning with an empty database for each test case. (If we were storing the database on the disk we would simply remove the file)
Our Setup
We are using Python's unittest module
(Python version: 3.6)
This is what our database creation looks like: db_connection = sqlite3.connect(":memory:")
How can we delete our database from memory?
Use the connection method close(). It will close your connection to the database. If the database is in memory, you should not be able to reconnect to it.
You can test this simply:
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE test (col1 text, col2 text)')
c.execute("INSERT INTO test VALUES ('good', 'day')")
conn.commit()
conn.close()
We can then check if we can access the database after.
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("SELECT * FROM test")
print(c.fetchall())
c.execute("SELECT * FROM test")
sqlite3.OperationalError: no such table: test
This shows us that when you close the database in memory, it is destroyed.

Insert into SQLite file Python - does not work

I have a simple database application in Python with SQLite. I wrote a simple program to create database and insert into some values. However, database is created, but new values are not inserted, and I don't know why:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
def CreateTable():
try:
connection = lite.connect(':memory:')
with connection:
cursor = connection.cursor()
sql = 'CREATE TABLE IF NOT EXISTS Authors' + '(ID INT PRIMARY KEY NOT NULL, FIRSTNAME TEXT, LASTNAME TEXT, EMAIL TEXT)'
cursor.execute(sql)
data = '\n'.join(connection.iterdump())
with open('authors.sql', 'w') as f:
f.write(data)
except lite.Error, e:
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
def Insert(firstname, lastname, email) :
try:
connection = lite.connect('authors.sql')
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, %s, %s, %s)" % (firstname, lastname, email)
cursor.execute(sql)
data = '\n'.join(connection.iterdump())
with open('authors.sql', 'w') as f:
f.write(data)
except lite.Error, e:
if connection:
connection.rollback()
finally:
if connection:
cursor.close()
connection.close()
CreateTable()
Insert('Tibby', 'Molko', 'tibby.molko#yahoo.co.uk')
You are not calling commit on your connection. You should also not write to the database file yourself, the database engine is writing to the file.
Try to go through the first few examples in sqlite documentation, it should be clear then.
You have misunderstood what connection.iterdump() is for. You are creating SQL text, instructions for SQLite to execute again at a later date. It is not the database itself. If all you wanted was to output SQL statements you can just write your SQL statements directly, there is little point in passing it through SQLite first.
You also cannot 'connect' SQLite to the text file with SQL statements; you'd have to load those statements as text and re-play them all. That's not what I think you wanted however.
You can connect to an existing database to insert additional rows. Each time you want to have add data, just connect:
def CreateTable():
connection = lite.connect('authors.db')
try:
with connection as:
cursor = connection.cursor()
sql = '''\
CREATE TABLE IF NOT EXISTS Authors (
ID INT PRIMARY KEY NOT NULL,
FIRSTNAME TEXT,
LASTNAME TEXT,
EMAIL TEXT)
'''
cursor.execute(sql)
finally:
connection.close()
def Insert(firstname, lastname, email) :
connection = lite.connect('authors.db')
try:
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, ?, ?, ?)"
cursor.execute(sql, (firstname, lastname, email))
finally:
connection.close()
Note that using the connection as a context manager already ensures that the transaction is either committed or rolled back, depending on there being an exception.
On the whole, you want to be informed of exceptions here; if you cannot connect to the database you'd want to know about it. I simplified the connection handling as such. Closing a connection auto-closes any remaining cursors.
Last but far from least, I switched your insertion to using SQL parameters. Never use string interpolation where parameters can be used instead. Using parameters makes it possible for the database to cache statement parse results and most of all prevents SQL injection attacks.
You cannot connect to a text file with sql commands.
sqlite3.connect expects or creates a binary file.
You didnt commit it.For writing into database, it should be committed.For read (select) operations,not needed.
try:
with connection:
cursor = connection.cursor()
sql = "INSERT INTO Authors VALUES (NULL, ?, ?, ?)"
cursor.execute(sql, (firstname, lastname, email))
connection.commit() # or cursor.commit()
finally:
connection.close()

Categories

Resources