在写代码之前,需要注意的一个问题是,使用命令行模式写MySQL语句,如果涉及到中文,最好利用 mysql>charset GBK;命令将客户端字符集设置为GBK,这样能保证正确插入和读取中文(数据库端字符集可以是gb2312,GBK,utf8等支持中文的字符集).
如果是利用Mysql 提供的 MySQL Query Browser 工具来写脚本,建议先在ultra edit等文本工具(最好别用记事本,因为可能有字符编码问题,推荐ultra edit)将代码写好,然后再粘贴到QueryBrowser 的Script Tab 中一并执行,因为QueryBrowser对中文的支持有bug,无法正确的输入中文,因此要先在别处写好。
写了几个表,里面包括外键主键的设置,建表语句如下:
USE testdatabase;
CREATE TABLE class (
class_id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
class_name VARCHAR(40)
);
CREATE TABLE student (
student_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(student_id),
student_name varchar(40),
class_id INTEGER UNSIGNED,
CONSTRAINT FK_student_class FOREIGN KEY(class_id) REFERENCES
class(class_id) ON DELETE CASCADE ON UPDATE CASCADE
);
CREATE TABLE lession(
lession_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (lession_id),
lession_name varchar(40)
);
CREATE TABLE core(
core_id INTEGER UNSIGNED AUTO_INCREMENT,
lession_id INTEGER UNSIGNED NOT NULL,
student_id INTEGER UNSIGNED NOT NULL,
core FLOAT,
close_status INTEGER DEFAULT 0,
CONSTRAINT PK_core PRIMARY KEY(
core_id
),
CONSTRAINT FK_core_lession FOREIGN KEY(lession_id) lession(lession_id),
CONSTRAINT FK_core_student FOREIGN KEY(student_id) student(student_id)
ON DELETE CASCADE
);
CREATE TABLE teacher(
teacher_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(teacher_id),
REFERENCES
REFERENCES
teacher_name varchar(40)
);
CREATE TABLE teachlession(
teachlession_id INTEGER PRIMARY KEY AUTO_INCREMENT,
lession_id INTEGER UNSIGNED,
teacher_id INTEGER UNSIGNED,
CONSTRAINT FK_teachlession_lession FOREIGN KEY(lession_id) REFERENCES lession(lession_id)
ON DELETE CASCADE,
CONSTRAINT FK_teachlession_teacher FOREIGN KEY(teacher_id) REFERENCES teacher(teacher_id)
ON DELETE CASCADE
);
CREATE TABLE sySUSEr(
sySUSEr_id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
sySUSEr_name VARCHAR(40),
sySUSEr_password VARCHAR(40),
sySUSEr_role INTEGER,
foreign_id INTEGER
);
/*这是指定表和列的字符集方式创建表*/
use testdatabase;
drop table if exists chartable;
create table chartable(
name varchar(30) character set utf8 collate utf8_general_ci
)character set latin1 collate latin1_danish_ci;
insert into chartable values('我们的世界');
一点总结:
1. 建表语句的顺序必须符合各个表之间的关系,比如主表应该在与之有外键关系的表之前建立。
2.关于外键的声明,两个字段的类型必须相同。
3.注意代码的编码格式和数据库字符集项符合。
因篇幅问题不能全部显示,请点此查看更多更全内容