Adapun codenya adalah sbb:
import MySQLdb
from time import gmtime, strftime
from random import randint
tgl=strftime("%Y-%m-%d", gmtime())
jam=strftime("%H:%M:%S", gmtime())
T=randint(25,40)
print 'waktu=',tgl,' jam ', jam
print 'T =',T ,' C'
db = MySQLdb.connect("localhost","root","","pythondb" )
cursor = db.cursor()
#cursor.execute("DROP TABLE IF EXISTS `tb_sensor`")
sql = """CREATE TABLE IF NOT EXISTS `tb_sensor` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`tanggal` date NOT NULL,
`jam` time NOT NULL,
`sensor` int(15) NOT NULL,
`status` varchar(15) NOT NULL,
`note` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3"""
try:
cursor.execute(sql)
except:
print('sukses membentuk tabel')
sql = 'INSERT INTO `tb_sensor` ( `tanggal`, `jam`, `sensor`, `status`, `note`) VALUES ("%s", "%s", "%d", "Y", "Sensor temperatur1")' % (tgl, jam, T)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
cursor.execute("SELECT * FROM tb_sensor")
count = 1
print 'No',' . ','ID',' | ','Tanggal',' | ','Jam',' | ','Sensor',' | ','Status',' | ','Note',' # '
print '=========================================================================# '
for row in cursor.fetchall():
print count,' . ',row[0],' | ',row[1],' | ',row[2],' | ',row[3],' | ',row[4],' | ',row[5],' # '
count = count + 1
db.close()
OK selamat mencoba friends.......
UNTUK UPDATE:
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","root","","pythondb" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to UPDATE required records sql = "UPDATE tb_sensor SET note = 'Sensor Lapangan 1' WHERE id = '%d'" % (1) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","root","","pythondb" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Prepare SQL query to DELETE required records sql = "DELETE FROM tb_sensor WHERE id> '%d'" % (20) try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
Tidak ada komentar:
Posting Komentar