kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

MySQL database

Wed Oct 19, 2016 11:11 pm

I am trying to store the DHT22 sensor readings in a MySQL database but for some reason it keeps getting stored in the DB as a NULL
how do I resolve this.
If I use dummy values like "33", "22" for the humidity and temp it saves but if I use the humidity or temperature variable then it doesnt save.

below is the code


#!/usr/bin/python
import RPi.GPIO as GPIO
import MySQLdb
import time
import Adafruit_DHT
dht_type = Adafruit_DHT.DHT22

try:
while True:
humidity, temperature = Adafruit_DHT.read_retry(dht_type, 18)
time.sleep(2)
try:
conn = MySQLdb.connect("localhost", "root", "Password1", "db1")
curs = conn.cursor()

curs.execute ("INSERT INTO sensor VALUES (curdate(), curtime(), humidity, temperature)") #this is not working - the date and time is saved in db but the humidity and temp values is a NULL value in the table

////curs.execute ("INSERT INTO sensor VALUES (curdate(), curtime(), 22, 33)") ---- this works but I obviously want to save the humidity and temp values not "33" and "22"

#Not exactly sure whats going on here and why its not working as expected.

conn.commit()
print "Data committed to Database"
except:
print "Error: the database is being rolled back"
conn.rollback()
conn.close()
curs.close()

W. H. Heydt
Posts: 10877
Joined: Fri Mar 09, 2012 7:36 pm
Location: Vallejo, CA (US)

Re: MySQL database

Thu Oct 20, 2016 3:57 am

Please post the schema for your table.

User avatar
lmarmisa
Posts: 1229
Joined: Thu Feb 14, 2013 2:22 am
Location: Jávea, Spain

Re: MySQL database

Thu Oct 20, 2016 4:09 am

You should not pass python variables to the INSERT command. You should pass the numeric values instead. I recommend this change:

Code: Select all

...
curscommand="INSERT INTO sensor VALUES (curdate(), curtime(), %d, %d)" %(humidity, temperature)
curs.execute (curscommand)
...

kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

Re: MySQL database

Thu Oct 20, 2016 6:15 am

To W. H. Heydt
Create table sensor (date DATE, time TIME, humidity REAL, Temp REAL)

To lmarmisa
Thank you for your help - I really did not know this.

User avatar
CarlRJ
Posts: 599
Joined: Thu Feb 20, 2014 4:00 am
Location: San Diego, California

Re: MySQL database

Thu Oct 20, 2016 6:34 am

Several points:
  • When you post code, especially Python code, where indentation is vital to meaning, always put it in

    Code: Select all

     ... 
    [/i] tags. Your code has two try keywords and one except keyword - there's no way to tell, for instance, which try the except a connected to.
  • The immediate problem you're having is because you are only passing the names of your variables in the string that contains the INSERT statement -- how is the code supposed to know that those bits of the string refer to your variables?
  • Despite the suggestion offered above, it's very important that you do not just use string interpolation to stuff the values of your variables directly into the string containing the INSERT statement - this would create a vulnerability in your code for an SQL injection attack. In this particular case, it probably wouldn't be a problem right now, but it's a bad habit to get into. Instead, let the MySQL client take care of putting the values into the query for you - the change might look minor (they both use "%s" in the query), but the effect is significantly different.
  • Along the way, it's best to explicitly name the columns that you're selecting from a table or inserting into a table - this will prevent heartache in the future if you add columns to the table.
  • Also, once a query gets long, it's nice to be able to break it up over several lines.
So, altogether, I think you want something like this (I use generally mysql.connector rather than MySQLdb, but I think this example ought to work for either):

Code: Select all

    curs.execute('''INSERT INTO sensor (date, time, humidity, Temp)
                    VALUES (curdate(), curtime(), %s, %s);''',
                 (humidity, temperature,))

kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

Re: MySQL database

Thu Oct 20, 2016 8:34 am

I appreciate your reply CarlRJ
I apologize for my inexperience but I'm here to learn and grow
Thank you very much for your help :)
lol - one day I will be on your level *hopefully

Graymalk
Posts: 55
Joined: Wed Nov 11, 2015 8:33 pm

Re: MySQL database

Thu Oct 20, 2016 2:52 pm

Just a comment... I don't know if this is "safe" or not but I often (or more like always lol) make everything in my table a varchar and then just cast when I need to. I find MySQL casts on its own which is exceedingly helpful (I find I only have to cast when using something like SQLite). So in the future you may be able to simplify your life by only ever working with strings. Potentially saves on space too because you can restrict the size to fit only your biggest expected number.

mfa298
Posts: 1387
Joined: Tue Apr 22, 2014 11:18 am

Re: MySQL database

Thu Oct 20, 2016 4:01 pm

Graymalk wrote:Just a comment... I don't know if this is "safe" or not but I often (or more like always lol) make everything in my table a varchar and then just cast when I need to. I find MySQL casts on its own which is exceedingly helpful (I find I only have to cast when using something like SQLite). So in the future you may be able to simplify your life by only ever working with strings. Potentially saves on space too because you can restrict the size to fit only your biggest expected number.
For pretty much all cases storing a number as a string will take more space than using an appropriate int type. For instance a TINYINT will take 1 byte of space and will store number from -127 to 128 (signed). Storing that same range as a varchar will require 2-5 bytes (a char would always require 4 bytes to store the same value).

Storing everything as a varchar is likely to have a negative impact on indexes as well in the DB as well as potentially hinder doing various operations on data that can be stored as a number (IPv4 IP addresses store nicely as a 4byte integer and let you do some interesting functions to determine all addresses in a network when stored in that way).

User avatar
CarlRJ
Posts: 599
Joined: Thu Feb 20, 2014 4:00 am
Location: San Diego, California

Re: MySQL database

Thu Oct 20, 2016 4:46 pm

kallasur wrote:I apologize for my inexperience but I'm here to learn and grow
Hey, no apologizes. I've learned a lot here too. I'm just trying to help where I can.
Graymalk wrote:Just a comment... I don't know if this is "safe" or not but I often (or more like always lol) make everything in my table a varchar and then just cast when I need to. ... So in the future you may be able to simplify your life by only ever working with strings. ...
On one hand, storing everything as varchars works, on the other, you're failing to take advantage of much of what a database is there to help you do. When you read a string from the database and then convert it to a floating-point number, say, nothing guarantees that the string you read actually represents a valid floating-point number - if it doesn't, how did that invalid value get there? Will the code that converts it fail and crash the program? Will it just silently continue? With what value? How will that affect your computations? Having the database store the field as a floating point number means it cannot ever accidentally end up with something else in it, so when you read it back, you can reasonably expect (vs. just assuming) that you're actually getting a number.

I'd recommend going in the other direction - make full use of the database's capabilities to ensure that only valid data is being stored. This eliminates entire categories of potential errors from your code, and errors that are not possible are errors you won't ever have to spend time tracking down.

In addition, if you store numbers as strings, you won't be able to have queries properly sort the results by those fields (because 10 > 3 but "10" < "3"), you won't be able to select values less than or greater than specific values (for the same reason), you won't be able to have the query add values together, or sum or average a column of numbers, or select the rows with the largest or smallest values. For a lot of potential uses, the database is not only capable of doing such things, but it has code to handle those things which has been extensively tested and debugged already, but you instead are taking the burden of doing those tasks upon yourself. It's a bit like having a car, but getting around by pushing it - you're missing out on its full potential, things it excels at because it was designed to do, and you're doing a lot of hard work yourself instead. ... So you're not simplifying your life, you're actually making it much harder.

Graymalk
Posts: 55
Joined: Wed Nov 11, 2015 8:33 pm

Re: MySQL database

Fri Oct 21, 2016 12:04 am

Actually, one huge advantage that strings have is that they *can* store an invalid value. Let's say you're trying to store a record that has a missing value. If the data type is a real, MySQL will automatically turn that into a zero, which has huge consequences because zero is *different*. So if I have an invalid piece of data, I want it to stay that way, not get converted by the engine.

Graymalk
Posts: 55
Joined: Wed Nov 11, 2015 8:33 pm

Re: MySQL database

Fri Oct 21, 2016 12:09 am

But I should add that my use case is statistics and machine learning, which may fall a little more closely to the original poster's plans and is why I posted. Someone who is writing software with different aims in mind (especially if there will be human interaction) will be more likely to assume a missing or invalid value is an error rather than something potentially interesting.

User avatar
CarlRJ
Posts: 599
Joined: Thu Feb 20, 2014 4:00 am
Location: San Diego, California

Re: MySQL database

Fri Oct 21, 2016 4:56 am

Graymalk wrote:Actually, one huge advantage that strings have is that they *can* store an invalid value. Let's say you're trying to store a record that has a missing value. If the data type is a real, MySQL will automatically turn that into a zero, which has huge consequences because zero is *different*. So if I have an invalid piece of data, I want it to stay that way, not get converted by the engine.
Ah, but then what you are trying to store are not numbers, but rather "textual data samples that might resemble numbers", in which case varchar is quite reasonable. And I was drawing more from SQL experience in general, and I'd forgotten that MySQL suffers from various forms of brain damage...

In particular, relevant to the current discussion, trying to insert a non-numeric value into a numeric field should always result in an error, not in having the database engine "helping" by substituting in a value like 0. In a proper SQL database, if the server has not been instructed otherwise, the insert statements for rows 4 and 5 (in the example below) should have simply failed*. Rows 2 and 3, by the way, show how to record a missing answer, distinct from 0.

*: (If you tell the database, "go paint the house blue", and it can't find blue paint, it should come back and say, "I can't paint the house blue, because I can't find blue paint" - MySQL seems to think the correct approach is to say, "Okay, the house is painted", and then you go and look and the house is painted yellow, because it could find yellow paint but not blue. That's not following instructions properly. Sigh.)

Code: Select all

mysql> CREATE TABLE tests ( foo INT NOT NULL, bar FLOAT, PRIMARY KEY (foo) );
...
mysql> DESCRIBE tests;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | NO   | PRI | NULL    |       |
| bar   | float   | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
...
mysql> INSERT INTO tests (foo, bar) VALUES (1, 5.0);
mysql> INSERT INTO tests (foo, bar) VALUES (2, NULL);
mysql> INSERT INTO tests (foo     ) VALUES (3);
mysql> INSERT INTO tests (foo, bar) VALUES (4, '');
mysql> INSERT INTO tests (foo, bar) VALUES (5, 'hello');
...
mysql> select * from tests;
+-----+------+
| foo | bar  |
+-----+------+
|   1 |    5 |
|   2 | NULL |
|   3 | NULL |
|   4 |    0 |
|   5 |    0 |
+-----+------+

kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

Re: MySQL database

Fri Oct 21, 2016 8:17 am

Thank you to everyone that replied - this really helped

Just a question :-
How do I now draw a graph on an HTML page using these humidity and temp values over time from the MYSQL db.

scotty101
Posts: 3711
Joined: Fri Jun 08, 2012 6:03 pm

Re: MySQL database

Fri Oct 21, 2016 8:38 am

kallasur wrote: Just a question :-
How do I now draw a graph on an HTML page using these humidity and temp values over time from the MYSQL db.
There are javascript libraries that will allow you to draw charts with minimal effort.
Try something like this http://www.chartjs.org/
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

Re: MySQL database

Fri Oct 21, 2016 8:49 am

Thank you scotty101

Is there a way to do it using HTML - currently most of my webpage is HTML and PHP.
I just want to conform to one standard. but if there is no other option than I will have to use Javascript.

User avatar
lmarmisa
Posts: 1229
Joined: Thu Feb 14, 2013 2:22 am
Location: Jávea, Spain

Re: MySQL database

Fri Oct 21, 2016 9:01 am

If you like PHP, I recommend JpGraph:

http://jpgraph.net/features/gallery.php

Heater
Posts: 13264
Joined: Tue Jul 17, 2012 3:02 pm

Re: MySQL database

Fri Oct 21, 2016 9:06 am

If you really want to stick to HTML generated on the server with PHP then one of the best ways to create simple charts and graphs is to use svg.

For example.
https://css-tricks.com/how-to-make-charts-with-svg/

There are PHP libraries to help generate such graphics:
http://www.goat1000.com/svggraph.php
http://www.pchart.net/

No doubt others around.

Personally I would bite the bullet and do it in Javascript on the page using D3 or plotly.js
https://plot.ly/javascript/
https://d3js.org/

Then you'll find yourself wanting to ditch the old PHP and Apache and do everything in Javascript using node.js as your server.

User avatar
DougieLawson
Posts: 36089
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: MySQL database

Fri Oct 21, 2016 9:10 am

If you clone https://github.com/raspberrypi/weather-station-www you'll get some sample code that reads a MySQL database and generates a collection of graphs.

There's even some ready made instructions for how to get it running at: https://www.raspberrypi.org/learning/we ... mo-site.md
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

Re: MySQL database

Fri Oct 21, 2016 9:12 am

I will go with the experts advice and try it in Javascript first.

kallasur
Posts: 82
Joined: Mon Dec 07, 2015 7:25 am

Re: MySQL database

Fri Oct 21, 2016 9:13 am

Thank you DougieLawson

I will gave a look :)


Excellent community
Very helpful

afedriansyah
Posts: 18
Joined: Mon Feb 26, 2018 6:32 am

Re: MySQL database

Mon Mar 12, 2018 2:39 am

Hi R-pi

I have created a touch screen buttons consist of "start" "Request material" "Receive material" "Lap" "Emergency" "Finish"
Now i am trying to store integers (as finish products) and lap times when an operator presses the lap button. the result shows in the terminal after i ran the program, but it didn't show in the mysql database. Here is my code can be seen below:

Code: Select all

from Tkinter import *
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
import time
import RPi.GPIO as GPIO
import MySQLdb


GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(0)
#-------------------------------------------------------GPIO
GPIO.setup(21, GPIO.OUT)#red led
GPIO.setup(20, GPIO.OUT)#yellow led
GPIO.setup(16, GPIO.OUT)#green led

GPIO.output(21, GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
#-------------------------------------------------------GPIO

class Screen(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
#-------------------------------------------------------Main
        self.lbttn_clicks = 0
        self.start_button()
        self.material_button()
        self.receive_button()
        self.emergency_button()
        self.lap_button()
        self.finish_button()
        self.minutes = 0
        self.seconds = 0
#-------------------------------------------------------Modbus Var
        self.LedRed_State = False
        self.LedYellow_State = False
        self.LedGreen_State = False
        self.db = MySQLdb.connect("localhost","root","raspberry","DB_ASSY")
        #self.sql = "INSERT INTO TAB_ASSY (Finished Product, Lap Time) VALUES (%s, %s)"
        self.c= self.db.cursor()
        self.client = ModbusClient('192.168.1.105')
        self.client.connect()
        print "ModbusClient connected..."
#-------------------------------------------------------Modbus Var
        
        self.time_start = time.time()
        self.pack(fill=BOTH, expand=1)
#-------------------------------------------------------Main

#-------------------------------------------------------Stopwatch
        self._start = 0.0
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()
        # self.makeWidgets()
#-------------------------------------------------------Stopwatch

#--------------------------------------------------------------------Main funcs
    def start_button(self):
        self.gbttn = Button(self)
        self.gbttn['text'] = "Start"
        self.gbttn['command'] = lambda: [ f() for f in  [self.Start, self.LedGreen, self.LedYellowOff, self.LedRedOff]]
        self.gbttn.place(x = 100, y = 0)

    def material_button(self):
        self.ybttn = Button(self)
        self.ybttn['text'] = "Request Material"
        self.ybttn['command'] = self.LedYellow
        self.ybttn.place(x=100, y=50)

    def receive_button(self):
        self.rbttn = Button(self)
        self.rbttn ['text'] = "Receive Material"
        self.rbttn ['command'] = self.LedYellowOff
        self.rbttn.place(x=100, y=100)

    def emergency_button(self):
        self.ebttn = Button(self)
        self.ebttn['text'] = "Emergency"
        self.ebttn['command'] = lambda: [f() for f in [self.LedRed, self.LedYellowOff, self.LedGreenOff]]
        self.ebttn.place(x=100,y=150)

    def lap_button(self):
        self.lbttn = Button(self)
        self.lbttn['text'] = "Lap"
        self.lbttn['command'] = lambda: [ f() for f in  [self.lap_count, self.Start, self.insert_to_db]]
        self.lbttn.place(x=100,y=200)

    def finish_button(self):
        self.fbttn = Button(self)
        self.fbttn['text'] = "Finish"
        self.fbttn['command'] = lambda: [f() for f in [self.Finish, self.Stop, self.Reset]]
        self.fbttn.place(x=100, y=250)

    def lap_count(self):
        self.lbttn_clicks += 1
        print str(self.lbttn_clicks)

    # def stop_watch(self):
    #     print self.seconds
    #     time.sleep(1)
    #     self.seconds = int(time.time() - self.time_start)
#--------------------------------------------------------------------------------------Main funcs

#--------------------------------------------------------------------------------------Modbus funcs
    
#--------------------------------------------------------------------------------------Modbus funcs

#--------------------------------------------------------------------------------------Stopwatch funcs
    # def makeWidgets(self):
    #     """ Print the time. """
    #     l = Label(self, textvariable=self.timestr)
    #     self._setTime(self._elapsedtime)
    #     l.pack(fill=X, expand=NO, pady=2, padx=2)
    def _print(self):
        print self._elapsedtime

    def _update(self):
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap / 60)
        seconds = int(elap - minutes * 60.0)
        hseconds = int((elap - minutes * 60.0 - seconds) * 100)
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

    def Start(self):
        """ Start the stopwatch, ignore if running. """
        print self._elapsedtime
        if not self._running:
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1
               
    def insert_to_db(self):
        self.sql = "INSERT INTO TAB_ASSY (Finished Product, Lap Time) where VALUES (%s, %s)"
        try:
            self.execute(sql,( str(self.lbttn_clicks), str(self._elapsedtime)))
            self.db.commit()
        except:
            self.db.rollback()
            
    def LedGreen(self):
        self.rr = self.client.read_coils(0,6)
        print "Start Button Pressed"
        if self.LedGreen_State == False:
            self.rr.bits[3] = True
            self.rq = self.client.write_coil(3, True)
            self.rq = self.client.write_coil(0, True)
            GPIO.output(16, GPIO.LOW)
            self.LedGreen_State = True
            
    def LedGreenOff(self):
        self.rr = self.client.read_coils(0,6)
        print "Green light is off"
        if self.LedGreen_State == True:
            self.rr.bits[3] = False
            self.rq = self.client.write_coil(3, False)
            self.rq = self.client.write_coil(0, False)
            GPIO.output(16, GPIO.HIGH)
            self.LedGreen_State = False
            
    def LedYellow(self):
        self.rr = self.client.read_coils(0,6)
        print "Request Material"
        if self.LedYellow_State == False:
            self.rr.bits[4] = True
            self.rq = self.client.write_coil(4, True)
            self.rq = self.client.write_coil(1, True)
            GPIO.output(20, GPIO.LOW)
            self.LedYellow_State = True
            
    def LedYellowOff(self):
        self.rr = self.client.read_coils(0,6)
        print "Material replenished"
        if self.LedYellow_State == True:
            self.rr.bits[4] = False
            self.rq = self.client.write_coil(4, False)
            self.rq = self.client.write_coil(1, False)
            GPIO.output(20, GPIO.HIGH)
            self.LedYellow_State = False
            
    def LedRed(self):
        self.rr = self.client.read_coils(0,6)
        print "Assembly process jammed"
        if self.LedRed_State == False:
            self.rr.bits[5] = True
            self.rq = self.client.write_coil(5, True)
            self.rq = self.client.write_coil(2, True)
            GPIO.output(21, GPIO.LOW)
            self.LedRed_State = True
            
    def LedRedOff(self):
        self.rr = self.client.read_coils(0,6)
        print "Red light is off"
        if self.LedRed_State == True:
            self.rr.bits[5] = False
            self.rq = self.client.write_coil(5, False)
            self.rq = self.client.write_coil(2, False)
            GPIO.output(21, GPIO.HIGH)
            self.LedRed_State = False
        
    def Finish(self):
        self.rr = self.client.read_coils(0,6)
        print "Assembly is finished"
        if self.LedGreen_State == True:
            self.rr.bits[3] = False
            self.rq = self.client.write_coil(3, False)
            self.rq = self.client.write_coil(0, False)
            GPIO.output(16, GPIO.HIGH)
            self.LedGreen_State = False
            
        if self.LedYellow_State == True:
            self.rr.bits[4] = False
            self.rq = self.client.write_coil(4, False)
            self.rq = self.client.write_coil(1, False)
            GPIO.output(20, GPIO.HIGH)
            self.LedYellow_State = False
            
        if self.LedRed_State == True:
            self.rr.bits[5] = False
            self.rq = self.client.write_coil(5, False)
            self.rq = self.client.write_coil(2, False)
            GPIO.output(21, GPIO.HIGH)
            self.LedRed_State = False   
        
    
    def Stop(self):
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)
            self._elapsedtime = time.time() - self._start
            self._setTime(self._elapsedtime)
            self._running = 0
            GPIO.cleanup()

    def Reset(self):
        """ Reset the stopwatch. """
        self._start = time.time()
        self._elapsedtime = 0.0
        self._setTime(self._elapsedtime)
        
    def main():
        while 1:
            insert_to_database()
              
        
        
        
        
#----------------------------------------------------------------------------------------------Stopwatch funcs

win = Tk()
win.title("Screen")
win.geometry('800x400')
app = Screen(win)

win.mainloop()
when i ran the script, there was no error but i did not show in the mysql database
I am using raspbian stretch by the way
please share
thank you
Last edited by afedriansyah on Wed Mar 14, 2018 1:22 am, edited 1 time in total.

User avatar
bob_binz
Posts: 441
Joined: Thu Feb 02, 2012 7:58 pm
Location: Stockport, UK

Re: MySQL database

Mon Mar 12, 2018 4:48 pm

Code: Select all

self.sql = "INSERT INTO TAB_ASSY (Finished Product, Lap Time) where VALUES (%s, %s)"
I think you have an erroneous "where". Try removing it.

Code: Select all

self.sql = "INSERT INTO TAB_ASSY (Finished Product, Lap Time) VALUES (%s, %s)"

BBz

afedriansyah
Posts: 18
Joined: Mon Feb 26, 2018 6:32 am

Re: MySQL database

Tue Mar 13, 2018 1:41 am

I tried it yesterday and it didn't work either. I've tried several things and the results were the same.
I think i should change around this code:

Code: Select all

def insert_to_db(self):
self.sql = "INSERT INTO TAB_ASSY ('Finished_Product',  'Time')  VALUES (%s, %s)"
try:
self.execute(sql,( str(self.lbttn_clicks), str(self._elapsedtime)))
self.c = self.db.cursor()
self.db.commit()
except:
self.db.rollback()

and

def main():
while 1:
insert_to_database()

and

if __name__ == '__main__':
     try:
         db = MySQLdb.connect("localhost","root","raspberry","DB_ASSY")
         self.c= self.db.cursor()

     except:
         print ("No connection to server...")
so when i ran the program the screen button appeared and there were no problems so far and in the terminal it showed, "No connection to server...". Well basically, it means it didn't connect to mysql database and didn't display in phpmyadmin table.

I honestly don't know what I did wrong in the python script and I am kinda stuck for now
I really need help with this
Thank you very much
Last edited by afedriansyah on Wed Mar 14, 2018 1:24 am, edited 2 times in total.

User avatar
DougieLawson
Posts: 36089
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: MySQL database

Tue Mar 13, 2018 2:01 pm

If you're going to post python code in the forum you MUST use [code][/code] tags.

That makes the difference between

def insert_to_db(self):
self.sql = "INSERT INTO TAB_ASSY ('Finished_Product', 'Time') VALUES (%s, %s)"

And

Code: Select all

def insert_to_db(self):
    self.sql = "INSERT INTO TAB_ASSY ('Finished_Product',  'Time')  VALUES (%s, %s)"
Python without the left-hand whitespace is undebuggable.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

afedriansyah
Posts: 18
Joined: Mon Feb 26, 2018 6:32 am

Re: MySQL database

Wed Mar 14, 2018 1:31 am

I just edited my post now the all the codes should be clear.
But i really still need help with my post above.
Thank you for your time

Return to “General discussion”