pythonデータベース操作-MySQL,SQLite

5336 ワード

MySQL
まずMySqldbモジュールのconnectメソッドを使用してMysSQLデーモンに接続します.接続メソッドは、データベース接続を返します.データベース接続のcursorメソッドを使用して、現在のデータベースのカーソルを取得します.その後、カーソルのExecuteメソッドを使用してSQL文を実行し、データベースの操作を完了できます.操作終了closeメソッドを呼び出してカーソルとデータベース接続を閉じます.
    import MySQLdb  ##  python Mysql   
    con = MySQLdb.connect(host='localhost',user='root',passwd='',db='testPython') ##       
    cur = con.cursor()  ##       
    cur.execute('insert into student (name,age,sex) values(\'jee\',21,\'F\')') ##    sql
    r = cur.execute('delete from student where age = 20') ##    sql
    con.commit() ##    
    cur.execute('select * from student') ##    sql
    r = cur.fetchall() ##    
    print r
    cur.close() ##    
    con.close() ##       

SQLite
まずsqlite 3モジュールをインポートし、SQLiteはサーバを必要としないのでconnectメソッドを使用してデータベースを開くだけです.connectメソッドは、データベース接続オブジェクトを返し、cursorメソッドを使用してカーソルを取得し、レコードを操作します.操作が完了したら、closeメソッドを使用してカーソルとデータベース接続を閉じます.
    import sqlite3
    con = sqlite3.connect('python') ##       
    cur = con.cursor()      ##       
    cur.execute('insert into student (name,age,sex) values(\'jee\',21,\'F\')')  ##    sql
    r = cur.execute('delete from student where age = 20')   ##    sql
    con.commit() ##    
    cur.execute('select * from student') ##    sql
    r = cur.fetchall() ##    
    print r

    cur.close() ##    
    con.close() ##