一、安裝MySQL
工作環(huán)境位于Ubuntu下肝断,首先安裝MySQL:
-
sudo apt-get install mysql-server
:需要設(shè)置登錄的root
密碼,兩次; apt-get isntall mysql-client
sudo apt-get install libmysqlclient-dev
確認(rèn)是否安裝完成:
sudo netstat -tap | grep mysql
夏块,如果看到mysql
的監(jiān)控狀態(tài)為listen
,表示安裝成功捐凭。
二拨扶、登錄及基本操作
以root
身份登錄mysql
數(shù)據(jù)庫(kù):
-
myslq -u root -p
:然后輸入密碼即可登錄;
數(shù)據(jù)庫(kù)的基本操作: 每個(gè)mysql
語(yǔ)句以分號(hào)結(jié)尾
//1茁肠、查看數(shù)據(jù)庫(kù)
show databases;
//2患民、創(chuàng)建數(shù)據(jù)庫(kù)
create database h_test;
//3、查看數(shù)據(jù)庫(kù)的創(chuàng)建基本信息:數(shù)據(jù)庫(kù)編碼等
show create database h_test;
//4垦梆、修改數(shù)據(jù)庫(kù)編碼位utf-8
alter database h_test default character set utf8;
//5匹颤、刪除數(shù)據(jù)庫(kù)
drop database h_test
表的基本操作
//1、切換到`h_test`數(shù)據(jù)庫(kù)
use h_test;
//2托猩、查看該數(shù)據(jù)庫(kù)中所有的表
show tables;
//3印蓖、創(chuàng)建表
create table user(id varchar(20), name varchar(20));
//4、插入條目
insert into user(id, name) values("1", "Kyxy");
//5京腥、查看表中的數(shù)據(jù)條目
select * from user;
三赦肃、Python3連接至MySQL數(shù)據(jù)庫(kù)
MySQL服務(wù)器以獨(dú)立進(jìn)程運(yùn)行,需要支持Python的MySQL驅(qū)動(dòng)來(lái)連接至MySQL服務(wù)器公浪。使用pymysql
模塊
- 安裝
pymysql
:pip3 install pymysql
- 使用:
#導(dǎo)入驅(qū)動(dòng)
import pymysql
#連接至test數(shù)據(jù)庫(kù)他宛,注意設(shè)置自己的登錄密碼
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd="password", db="test")
cursor = conn.cursor()
cur.execute("SELECT * FROM test")
#提交事務(wù)
conn.commit()
#關(guān)閉數(shù)據(jù)庫(kù)連接
conn.close()
- 在表中插入數(shù)據(jù):
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
#create base class
Base = declarative_base()
#define class mapping to the table
class User(Base):
#__tablename__的寫(xiě)法不要錯(cuò)了
__tablename__ = 'user'
id = Column(String(20), primary_key=True)
name = Column(String(20))
#initialize the connect to database
#注意本機(jī)上的端口使用的是3306
engine = create_engine("mysql+pymysql://root:password@localhost:3306/test")
DBSession = sessionmaker(bind = engine)
session = DBSession()
new_user = User(id='2', name='Tracy')
session.add(new_user)
session.commit()
session.close()