LoginSignup
0
0

More than 1 year has passed since last update.

PythonとSQLiteを使ってみた

Last updated at Posted at 2022-07-02

仕事ではJavaやJavaScriptが多いですが、個人的にはpythonが好きです。
pythonの現場に行く機会があった時にできるようになっていたいなあとなるべく毎日勉強しています。

今回はpythonに標準であるSQLiteを使って基本的なことをやってみました。
まず、DB作成からテーブル、データのinsertまで。

import sqlite3

#データベースファイルを作る
dbfile = sqlite3.connect('fruit.db')
c = dbfile.cursor()

createSql = 'create table FruitName(id,name);'
c.execute(createSql)

insertSql = "insert into FruitName(1,'Apple');"
c.execute(insertSql)

dbfile.commit()
dbfile.close()

作成したテーブル内のデータを表示するためのソースがこちら

import sqlite3

connectDb = sqlite3.connect("fruit.db")
c = connectDb.cursor()

for row in c.execute('select * from FruitName'):
    print(row)
connectDb.close()

データが表示されました。
image.png

同じデータが2個入っているのはinsert後のソースでエラーが出て、直してからもう一度実行することによりinsertが2回動いたためです。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0