Databases

Databases

Creating a Table

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(6) unsigned NOT NULL,  
  `username` varchar(200) NOT NULL,
  `role` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
);
  • NOT NULL - Each row must contain a value for that column, null values are not allowed
  • DEFAULT value - Set a default value that is added when no other value is passed
  • UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
  • AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added
  • PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT

Inserting Data

INSERT INTO `users` (`id`, `username`, `role`) VALUES
  ('1', 'Kelvin', 'Tutor'),
  ('2', 'Tina', 'Tutor'),
  ('3', 'Stephen', 'Tutor'),
  ('4', 'Artem', 'Lecturer');

Retrieving Data

全选

SELECT *
FROM users

选择所有列

选择某一列

SELECT username, role
FROM users

查询选择

SELECT *
FROM users
WHERE role = 'Tutor'

选择固定行数数据

SELECT *
FROM users
WHERE role = 'Tutor'
LIMIT 2

选择排序后结果

SELECT *
FROM users
WHERE role = 'Tutor'
ORDER BY id DESC

DESC 降序, ASC 升序[http://www.sqlitetutorial.net/sqlite-order-by/]

更新数据

UPDATE users
SET role = 'Lecturer'
WHERE username = 'Stephen';

先查后更新

删除数据

DELETE FROM users
WHERE username = 'Stephen';

先查后删除

Foreign key

FOREIGN KEY是用于将两个表链接在一起的键。

FOREIGN KEY是一个表中的一个字段(或字段集合),它引用另一个表中的PRIMARY KEY。

包含foreign key 的表称为子表,包含primary key的表称为引用表或父表。

FOREIGN KEY约束用于防止会破坏表之间链接的操作。

FOREIGN KEY约束还可以防止将无效数据插入到外键列中,因为它必须是它指向的表中包含的值之一。

CREATE TABLE IF NOT EXISTS staff (
  staff_id int(6) NOT NULL,
  username varchar(200) NOT NULL,
  PRIMARY KEY (staff_id)
);

INSERT INTO staff (staff_id, username) VALUES
  ('1', 'Kelvin'),
  ('2', 'Harrison'),
  ('3', 'Stephen'),
  ('4', 'Prasad'),
  ('5', 'David');

CREATE TABLE IF NOT EXISTS roles
(
  role_id int(6) NOT NULL,
  staff_id int(6) NOT NULL,
  role varchar(200),
  unit varchar(200),
  PRIMARY KEY (role_id),
  FOREIGN KEY (staff_id) REFERENCES staff(staff_id)
);

INSERT INTO roles (role_id, staff_id, role, unit) VALUES
  ('1', '1', 'Tutor', 'BUSS6002'),
  ('2', '2', 'Tutor', 'BUSS6002'),
  ('3', '3', 'Lecturer', 'BUSS6002'),
  ('4', '3', 'Tutor', 'BUSS6002'),
  ('5', '4', 'Tutor', 'BUSS6002'),
  ('6', '1', 'Tutor', 'QBUS6810');
staff_id username
1 Kelvin
2 Harrison
3 Stephen
4 Prasad
5 David
role_id staff_id role unit
1 1 Tutor BUSS6002
2 2 Tutor BUSS6002
3 3 Lecturer BUSS6002
4 3 Tutor BUSS6002
5 4 Tutor BUSS6002
6 1 Tutor QBUS6810

Join

SELECT staff.username, roles.role, roles.unit
FROM roles
INNER JOIN staff ON staff.staff_id = roles.staff_id
username role unit
Kelvin Tutor BUSS6002
Kelvin Tutor QBUS6810
Harrison Tutor BUSS6002
Stephen Lecturer BUSS6002
Stephen Tutor BUSS6002
Prasad Tutor BUSS6002

David is not present in both tables

SQLITE3

基本操作(连接、执行、查看)

import sqlite3

conn = sqlite3.connect("staff.db")

c = conn.cursor()

c.execute("SELECT roles.role, roles.unit FROM roles")

c.fetchall()
  • sqlite3.connect(database [,timeout ,other optional arguments])

该 API 打开一个到 SQLite 数据库文件 database 的链接

  • connection.cursor([cursorClass])

该例程创建一个 cursor对象,

Once you have a Connection, you can create a Cursor object and call its execute() method to perform SQL commands

  • cursor.execute(sql [, optional parameters])

该例程执行一个 SQL 语句。该 SQL 语句可以被参数化(即使用占位符代替 SQL 文本)

  • cursor.fetchall()

该例程获取查询结果集中所有(剩余)的行,返回一个列表。当没有可用的行时,则返回一个空的列表

[('Tutor', 'BUSS6002'),
 ('Tutor', 'BUSS6002'),
 ('Lecturer', 'BUSS6002'),
 ('Tutor', 'BUSS6002'),
 ('Tutor', 'BUSS6002'),
 ('Tutor', 'QBUS6810')]

导入数据到Pandas

import pandas as pd

conn = sqlite3.connect("staff.db")

roles_df = pd.read_sql("SELECT roles.role, roles.unit FROM roles", conn)

roles_df.head()
role unit
0 Tutor BUSS6002
1 Tutor BUSS6002
2 Lecturer BUSS6002
3 Tutor BUSS6002
4 Tutor BUSS6002

Remote Database

对于不同的数据库类型,create_engine的参数也不一样

The create_engine() function produces an Engine object based on a URL. These URLs follow RFC-1738, and usually can include username, password, hostname, database name as well as optional keyword arguments for additional configuration. In some cases a file path is accepted, and in others a “data source name” replaces the “host” and “database” portions. The typical form of a database URL is:

dialect+driver://username:password@host:port/database

sqlalchemy.create_engine(*args, **kwargs)

The string form of the URL is dialect[+driver]://user:password@host/dbname[?key=value..],

dialect is a database type such as mysql, oracle, postgresql, etc.,

driver the name of a DBAPI, such as psycopg2, pyodbc, cx_oracle, etc.

username the username we use to connect to the database with. Different users may have different permissions

password the password for the user

host is the domain name where the database is hosted

portthe port to use when connecting. When you go to a website you are using port 80.

databasethe name of the database. The server can have multiple databases.

SQLite

db = create_engine('sqlite:///staff.db')

roles_df = pd.read_sql("SELECT roles.role, roles.unit FROM roles", db)

roles_df.head()
role unit
0 Tutor BUSS6002
1 Tutor BUSS6002
2 Lecturer BUSS6002
3 Tutor BUSS6002
4 Tutor BUSS6002

PostgreSQL

from sqlalchemy import create_engine
engine = create_engine('postgresql://scott:tiger@localhost:5432/mydatabase')
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,423评论 0 13
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,243评论 0 23
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,254评论 0 10
  • ORACLE自学教程 --create tabletestone ( id number, --序号usernam...
    落叶寂聊阅读 1,055评论 0 0
  • 活动目标: 理解观察的方法,激发幼儿发现物体异同的兴趣。 锻炼幼儿的观察能力,积极参与活动。 结合生活经验,...
    沫熙晨阅读 416评论 0 1