PythonでSQL(UPDATE/DELETE/DROP TABLE)を実行する方法(SQLite)です
レコードを更新するSQLを実行します
1 | c.execute( "UPDATE test_table SET name = 'AAA' WHERE id = '1'" ) |
レコードを削除するSQLを実行します
1 | c.execute( "DELETE FROM test_table WHERE id = '2'" ) |
テーブルを削除するSQLを実行します
1 | c.execute( "DROP TABLE test_table" ) |
全体の流れ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import sqlite3 # Connection 接続 conn = sqlite3.connect( 'test.db' ) # Cursor 取得 c = conn.cursor() # SQL 実行 テーブル作成 c.execute( 'CREATE TABLE test_table(id integer, name text)' ) # SQL 実行 レコード追加 c.execute( "INSERT INTO test_table VALUES ('1','aaa')" ) c.execute( "INSERT INTO test_table VALUES ('2','bbb')" ) # SQL 実行 レコード更新 c.execute( "UPDATE test_table SET name = 'AAA' WHERE id = '1'" ) # SQL 実行 レコード削除 c.execute( "DELETE FROM test_table WHERE id = '2'" ) # SQL 実行 レコード取得 for row in c.execute( 'SELECT * FROM test_table ORDER BY id' ): print (row) # SQL 実行 テーブル削除 c.execute( "DROP TABLE test_table" ) # Commit 実行 conn.commit() # Connection 切断 conn.close() |