Python ÇÁ·Î±×·¡¹Ö > sqlite3 - pysqlite °³³ä¹× ¿¹Á¦
µî·ÏÀÏ : 2017-08-03 10:43
Á¶È¸¼ö : 53,142
Python¿¡¼ SQLite À» »ç¿ëÇϱâ À§Çؼ´Â º¸Åë pysqlite À¸·Î ºÒ¸®¿ì´Â Language binding (ÁÖ: SQLite ¶óÀ̺귯¸®¸¦ ³»ºÎ¿¡¼ »ç¿ë)À» »ç¿ëÇϴµ¥, pysqlite Àº Python 2.5 À̻󿡼 ±âº»ÀûÀ¸·Î ³»ÀåµÇ¾î ÀÖ´Ù.
pysqlite ¸¦ import Çϱâ À§Çؼ´Â ¾Æ·¡¿Í °°ÀÌ "import sqlite3" ¸¦ »ç¿ëÇÑ´Ù.
$ python
Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 19 2015, 20:19:30)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> sqlite3.version
'2.6.0'
>>>
À§ ¿¹Á¦´Â sqlite3 ÀÇ ¹öÀüÀ» È®ÀÎÇÏ´Â ¿¹Á¦ ÀÔ´Ï´Ù.
ÀÌÁ¦ µ¥ÀÌÅͺ£À̽º¸¦ ¸¸µé°í, Å×À̺íÀ» ¸¸µçÈÄ °£´ÜÇÑ µ¥ÀÌÅ͸¦ ÀúÀåÇÏ°í, Àоî¿À´Â ¿¹Á¦¸¦ º¸µµ·Ï ÇÏ°Ú½À´Ï´Ù.
import sqlite3 as sq
con = sq.connect("ankyu.db")
cursor = con.cursor()
#insert DB
def InsertDB() :
print("InsertDB()")
cursor.execute("create table suspect5(Name text, price int)")
cursor.execute("insert into suspect5(Name,price) values('Ã־ȱÔ',10000)")
cursor.execute("insert into suspect5(Name,price) values('Å×½ºÆ®',20000)")
cursor.execute("insert into suspect5(Name,price) values('È«±æµ¿',30000)")
con.commit()
con.close
#Read DB
def ReadDB() :
print("ReadDB()")
cursor.execute("select * from suspect5")
for result in cursor:
print(result)
def main() :
InsertDB()
ReadDB()
if __name__ == "__main__" :
main()
SQLite¸¦ »ç¿ëÇϱâ À§Çؼ´Â ¿ì¼± »ç¿ëÇÒ db ÆÄÀÏ (¿¹: ankyu.db)À» sqlite3.connect() ¸Þ¼µå·Î ¿ÀÇÂÇÏ°í, SQL Äõ¸®¸¦ ½ÇÇàÇÏ¿© µ¥ÀÌŸ¸¦ »ç¿ëÇÑ ÈÄ, ¸¶Áö¸·¿¡ ConnectionÀ» ´ÝÀ¸¸é µÈ´Ù.
DB ConnectionÀÌ ¿¬°áµÇ¸é Connection °´Ã¼°¡ ¸®ÅϵǴµ¥, ÀÌ °´Ã¼·ÎºÎÅÍ Ä¿¼¸¦ »ý¼ºÇÏ°í Ä¿¼ °´Ã¼ÀÇ execute() ¸í·ÉÀ» ½ÇÇàÇÏ¿© SQL Äõ¸®¸¦ ½ÇÇàÇÑ´Ù.
À§ À̹ÌÁö¿¡¼ »¡°£¹Ú½º¸¦ º¸¸é test.py ¸¦ ½ÇÇàÇØ º» °á°ú°¡ ȸ鿡 ÂïÈ÷´Â °É È®ÀÎÇÒ ¼ö ÀÖ½À´Ï´Ù.
1. ankyu.db ÆÄÀÏÀ» ¸¸µçÈÄ
2. InsertDB() ÇÔ¼ö¿¡¼ suspect5 Å×À̺íÀ» ¸¸µé°í, µ¥ÀÌÅ͸¦ ÀúÀåÇÕ´Ï´Ù.
3. ReadDB() ÇÔ¼ö¿¡¼ suspect5 ³»¿ëÀ» Àоî¿Í¼ Ãâ·ÂÇÕ´Ï´Ù.
°£´ÜÇÑ Å×½ºÆ® ¿¹Á¦¸¦ ¸¸µé¾î º¸¾Ò½À´Ï´Ù.