Sabtu, 24 September 2016

Koneksi Mysql menggunakan Python

1.setting path python dahulu....




2.download driver mysql-python for windows
https://pypi.python.org/pypi/MySQL-python/1.2.5

lalu install:

3.buat database dan tabel di localhost/phpmyadmin



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 ;

--
-- Dumping data for table `tb_sensor`
--

INSERT INTO `tb_sensor` (`id`, `tanggal`, `jam`, `sensor`, `status`, `note`) VALUES
(1, '2016-09-25', '10:00:00', 35, 'Y', 'Sensor temperatur1'),
(2, '2016-09-25', '10:10:00', 36, 'Y', 'Sensor temperatur1');


4.buat code sbb

import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="root",         # your username
                     passwd="",  # your password
                     db="pythondb")        # name of the data base

cur = db.cursor()
cur.execute("SELECT * FROM tb_sensor")

count = 1
print 'No',' . ','ID',' | ','Tanggal',' | ','Jam',' | ','Sensor',' | ','Status',' | ','Note',' # '
print '=========================================================================# '
for row in cur.fetchall():
print count,' . ',row[0],' | ',row[1],' | ',row[2],' | ',row[3],' | ',row[4],' | ',row[5],' # '
count = count + 1
db.close()

Lalu jalankan:

OK Sip.....Selanjutnya tinggal CRUD: Create, Read, Update, Delete




Tidak ada komentar:

Posting Komentar