Data connection to the database operations related

SQLite is an embedded database, it is a database file. Since SQLite itself is written in C, and the volume is very small, built on the SQLite3 Python, so using SQLite in Python, no need to install anything directly.

Python API interface defines a set of database operations, Python be connected to any database, the database need only provide the drive to meet the standard Python. Since the drive built-in SQLite Python standard library, it can be operated directly SQLite database.

In Python database operation, the database corresponding drive first introduced, and then the Connection object and operation data Cursor object. After the database is finished, make sure to open the Connection object and Cursor objects are closed properly, otherwise it will leak resources.

 


import sqlite3,os
# Connect to the SQLite database
# Database file is lhrtest.db
# If the file does not exist, it will automatically create a database file in the current directory:
conn = sqlite3.connect('lhrtest.db')
 
# db_file = os.path.join(os.path.dirname(__file__), 'lhrtest.db')
# If os.path.isfile (db_file): If the database exists
#     os.remove(db_file)
# conn = sqlite3.connect(db_file)
 
# Create a Cursor:
cursor = conn.cursor()
# Execute a SQL statement, create a user table:
cursor.execute('create table user(id varchar(20) primary key, name varchar(20))')
# Continue to execute a SQL statement to insert a record:
cursor.execute('insert into user (id, name) values (\'1\', \'xiaomaimiao\')')
# Get the number of rows inserted through rowcount:
print(cursor.rowcount)
# Execute a query:
cursor.execute('select * from user where id=?', ('1',))
# Obtain a query result set:
values = cursor.fetchall()
print(values)
# Close Cursor:
cursor.close()
# Commit the transaction:
conn.commit()
# Close Connection:
conn.close()
 
operation result
  1.  
    1
  2.  
    [( '. 1',  'xiaomaimiao')]

In the end it will generate a folder

lhrtest.db file

 

 And then view the data edit data using data management tools.

So when you need to perform general sql statement execution using the execute method.

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/1208xu/p/11963339.html