How to pass sqlite db values to controller - html

Newbie in sqlite, web2py. Am trying to copy sqlite db contents to controller for another function.
My codes are these:
db.py
auth.define_tables(username=False, signature=False)
auth.settings.registration_requires_verification = False
auth.settings.registration_requires_approval = False
auth.settings.reset_password_requires_verification = True
db.define_table('chat',
Field('me_from'),
Field('me_body', 'text'),
default:
#auth.requires_login()
def index():
chats.index(db)
body = db.chat.me_body()
rows = db(db.chat.me_body).select()#(orderby=~db.chat.me_body.created_on)
form1 = [body]
form5 = form1#.split()
name3 = ' '.join(form5)
I want t retrieve a string posted to db..
chat.id chat.me_from chat.me_body chat.me_html
1
2 maurice hi <div class="m...
3 maurice whats up <div class="m...
4 maurice where are you. <div class="m...
5 maurice 3i5ejp[eoityjdt <div class="m...
6 maurice how are you d...<div class="m...
7 maurice britam <div class="m...
From the table above, i want to retrieve from chat.me_body the posted words such as, 'hi', 'whats up', 'britam'... to default function. I instead keep getting the following errors:
If I use:
body = db.chat.me_body()
the error is:
TypeError: 'Field' object is not callable
If I use:
`body = db.chat.me_body
The error is:
TypeError: sequence item 0: expected string, Field found
If I use rows:
rows = db(db.chat.me_body).select()
and
form1 = [rows]
the error is:
name3 = ' '.join(form5)
TypeError: sequence item 0: expected string, Rows found
I I'll appreciate your help

The proper way to do a query to get records from the database is:
rows = db(db.chat).select(db.chat.me_body, db.chat.created_on,
orderby=~db.chat.created_on)
Note, db(db.chat) is shorthand for the query db(db.chat.id != None) (i.e., selection of all records in the table).
Then, to extract just the me_body field values into a list, you can use a list comprehension:
me_body_values = [r.me_body for r in rows]
Finally, you can join those values together:
name3 = ' '.join(me_body_values)

Related

How do I get a "clean" string from MySQL?

I run this code in python 3.6 (pythonanywhere.com) using MySQL
import MySQLdb
conn = MySQLdb.connect('username.mysql.pythonanywhere-services.com', 'username', 'password', 'username$to_do')
c = conn.cursor()
c.execute('SELECT task FROM list')
rows = c.fetchall()
list_em = []
number = 0
for eatchRow in rows:
list_em.append(eatchRow)
print("nr %s: %s" % (number, list_em[number]))
number += 1
del1 = int(input("Chose the number of the list item you want to delete: "))
delstatmt = "DELETE FROM list WHERE task = ?"
print (list_em[del1])
#c.execute(delstatmt, (list_em[del1],))
I am creating a list called "list_em" and fill with the content from the column "task" in the table "list". I would like "print (list_em[del1])" to return 'Gå med hunden' -A clean string that I can use to run the last script that is commented out. Instead get something that looks like this with brackets and a comma(from console):
nr 0: ('Skura Trappan',)
nr 1: ('Gå med hunden.',)
Chose the number of the list item you want to delete: 1
('Gå med hunden.',)
OBS! The table does not have any ID, just two columns:
mysql> select * from list;
+-----------------+-------------+
| task | status |
+-----------------+-------------+
| Skura Trappan | Not started |
| Gå med hunden. | Not started |
+-----------------+-------------+
2 rows in set (0.00 sec)
What you're getting back from the MySQL library is a list of tuples, one for each row returned by the query. The elements of each tuple are the values of the columns you're querying for.
In this case, you're querying for one column, so each element of the list is a one-element tuple, which Python will represent as (value,) -- which is what you're seeing.
So in order to print out just the value from the tuple, you need to extract it, just like you would with a list:
for eatchRow in rows:
list_em.append(eatchRow[0])
print("nr %s: %s" % (number, list_em[number]))
number += 1

Multiple WHERE conditions using AND => No query result

I have a table with a few thousand entries. And My purpose is to select all entries from all versions that correspond to a given one. And the resulted entries must correspond exactly to the given entry.
But somehow, the SQL query does not work. The original project uses Access 2007. But I have tried also in MySQL and no success
I put here the sql query, but I also made a SQL fiddle:
SELECT
idvalue,
idtag,
iddevice,
idversion,
idtext,
description,
idaccess,
defaultvalue,
minimumvalue,
acceptedvalue,
maximumvalue,
outofrangevalue,
iddatatypepn,
iddatatypeopc,
size,
idresolution,
idunit,
idaccuracy,
enumerationvalues,
comments,
remanentvolatile,
storedatpn,
storedatmain,
`generated`,
edittime
FROM
SomeValues
WHERE
idtag = 2 AND iddevice = 1
AND idtext = 433
AND description = 'Input voltage (AC)'
AND idaccess = 12
AND defaultvalue IS NULL
AND minimumvalue =0
AND acceptedvalue = 5300
AND maximumvalue = 10050
AND outofrangevalue = 11000
AND iddatatypepn = 2
AND iddatatypeopc = 19
AND size = 2
AND idresolution = 2
AND idunit = 1
AND idaccuracy = 2
AND enumerationvalues IS NULL
AND comments IS NULL
AND remanentvolatile IS NULL
AND storedatpn = FALSE
AND storedatmain = FALSE
AND `generated` = TRUE
Fiddle: here
Can you please explain what is wrong with the sql query?
The result should be those 3 entries from the fiddle table.
And yes, I must use all the conditions from the "Where" clause, since the entries can match 90% but also have small differences
You have problem in line:
AND description = 'Input voltage (AC)'
change it to:
AND description = '"Input voltage (AC)"'
and everything will works.
Problem lies in the fact that you searched for text Input voltage (AC) instead of "Input voltage (AC)" (how is stated in column description).

search for text within string in laravel or mysql

I use my SQL as backend for my project, and I need to get all record from database where some part of inputted string is available in database string like:
table = seller
id company_name seller_name
1 companyname1 seller1
2 companyname2 seller2
3 companyname3 seller3
4 companyname4 seller4
Given string is 1105 companyname1 is outstanding
So i need to get id = 1 for a given string if it is possible with laravel or MySQL then please help me.
You can construct a query using like:
where $YourString like concat('%', companyname, '%')
Note: There are situations where one company name might be sufficiently like another ("company1" and "company10"). If this is an issue, regular expressions might help.
First, you have to convert that string to an array.
$str = "1105 companyname1 is outstanding";
$str = explode(' ' , $str);
$results = Seller::whereIn('company_name' , $str)->get();
Note:
As you are converting random strings to an array, there will be a mistake where the user input some more spaces.
Let say the user input a string like $str = "1105 companyname1 is outstanding"; this will create some more elements. Like
array(
0 => '1104',
1 => '',
2 => 'companyname1',
3 => 'is',
4 => 'outstanding'
)
So, to avoid that, I have to recommend you to split out some more spaces. You can do by
$str = preg_split('/\s+/', $string, -1, PREG_SPLIT_NO_EMPTY);

Subquerying in Django

I have a Django 1.9 project implementing small chat app. All messages from a certain recipient are grouped into dialogs, so the models are defined as follows:
class Dialog(models.Model):
# Some fields
class Message(models.Model):
dialog = models.ForeignKey(Dialog, ...)
text = models.TextField()
is_read = models.BooleanField(default = False)
My goal is to render a template with a table that renders dialogs. And for each dialog in the table, I need to see
the number of unread messages and
the text of the last message.
To illustrate, consider mock-data below:
Input:
id dialog_id message is_read
1 1 Hello, sir false
2 1 My name is true
3 1 Jack true
4 2 This site false
5 2 is perfect false
6 2 Cheers false
Desired output:
dialog_id last_message_in_dialog unread_messages_count
1 Jack 1
2 Cheers 3
In pure mysql, I would write a query like this:
select
a.dialog_id,
text as last_message_in_dialog,
(select count(*) from message
where dialog_id = a.dialog_id and is_read = false) as unread_messages_count
from message a
where id in (select max(id) from message group by dialog_id)
In Django terms, I have the code below:
max_id_qs = Message.objects.\
values('dialog__id').\
annotate(max_id = Max('id'),).values('max_id')
qs = Message.objects.filter(id__in = max_id_qs).\
values('dialog__id', 'text')
This code serves well to fetch the last message in each dialog. However, the problem is that I can't figure out how to implement the subquery (select count(*) from message where dialog_id = a.dialog_id and is_read = false) in Django. Maybe my total approach with max_id_qsis wrong, and there's more elegant and clear way to implement the query in Django ORM?
I've spent an entire day trying to solve this issue. help me please !
This will work :-
allDistinctIdWithNotReadMsg =
Message.objects.filter(is_read=False).values('id').annotate(the_count=Count('is_read',distinct('id')))
for ids in allDistinctIdWithNotReadMsg:
lastMsg = Message.objects.filter(dialog_id=ids['id']).order_by("-id")[0]
for msg in lastMsg:
print ids['id'] ,msg.message,ids['the_count']

MySQL Query Problems for error ''

Hi all i have been writing a query and it is driving me crazy because it is giving me syntax error for ''
my query is
UPDATE test1 SET result =
CASE WHEN formula = "p1+p2" THEN 2
the error is here on line 2
any help is highly appreciated.
A case should always have an end:
UPDATE test1
SET result = (CASE WHEN formula = 'p1+p2' THEN 2 END);
This sets result to either "2" or NULL. You probably want:
UPDATE test1
SET result = 2
WHERE formula = 'p1+p2';
As a general rule, use single quotes for string constants. This is the ANSI standard.