Python3实现连接SQLite数据库的方法,python3sqlite
Python3实现连接SQLite数据库的方法,python3sqlite
本文实例讲述了Python3实现连接SQLite数据库的方法,对于Python的学习有不错的参考借鉴价值。分享给大家供大家参考之用。具体方法如下:
实例代码如下:
import sqlite3 db = r"D:\pyWork\test.db" #pyWork目录下test.db数据库文件 drp_tb_sql = "drop table if exists staff" crt_tb_sql = """ create table if not exists staff( id integer primary key autoincrement unique not null, name varchar(100), city varchar(100) ); """ #连接数据库 con = sqlite3.connect(db) cur = con.cursor() #创建表staff cur.execute(drp_tb_sql) cur.execute(crt_tb_sql) #插入记录 insert_sql = "insert into staff (name,city) values (?,?)" #?为占位符 cur.execute(insert_sql,('Tom','New York')) cur.execute(insert_sql,('Frank','Los Angeles')) cur.execute(insert_sql,('Kate','Chicago')) cur.execute(insert_sql,('Thomas','Houston')) cur.execute(insert_sql,('Sam','Philadelphia')) con.commit() #查询记录 select_sql = "select * from staff" cur.execute(select_sql) #返回一个list,list中的对象类型为tuple(元组) date_set = cur.fetchall() for row in date_set: print(row) cur.close() con.close()
希望本文实例对大家的Python学习有所帮助。
import sqlite3
conn = sqlite3.connect("test.db")
conn.execute("PRAGMA journal_mode = wal")
conn.commit()
cu = conn.cursor()
..
package xiaohang.zhimeng;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteDatabase.CursorFactory;public class MySQLiteHelper extends SQLiteOpenHelper{//调用父类构造器public MySQLiteHelper(Context context, String name, CursorFactory factory,int version) {super(context, name, factory, version);}/*** 当数据库首次创建时执行该方法,一般将创建表等初始化操作放在该方法中执行.* 重写onCreate方法,调用execSQL方法创建表* */@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL("create table if not exists hero_info("+ "id integer primary key,"+ "name varchar,"+ "level integer)");}//当打开数据库时传入的版本号与当前的版本号不同时会调用该方法@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}使用这个类来创建一个数据库 并对数据库进行操作MySqliteHelper myHelper = new MySQLiteHelper(this, "my.db", null, 1);SQLiteDatabase db = myHelper.getWritableDatabase(); db.execSQL("insert into hero_info(name,level) values('bb',0)");execSQL()里是你的SQL语句
评论关闭