以下是一些常见数据库的基本操作语句,包括创建数据库、创建表、插入数据、查询数据、更新数据和删除数据等操作:
MySQL
- 创建数据库:
CREATE DATABASE IF NOT EXISTS my_database;
- 使用数据库:
USE my_database;
- 创建表:
CREATE TABLE students ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, age INT, gender ENUM('男', '女') );
- 插入数据:
INSERT INTO students (name, age, gender) VALUES ('张三', 20, '男'); INSERT INTO students (name, age, gender) VALUES ('李四', 22, '女'), ('王五', 21, '男');
- 查询数据:
-- 查询所有学生信息 SELECT * FROM students; -- 查询年龄大于20岁的学生姓名和年龄 SELECT name, age FROM students WHERE age > 20; -- 按照年龄升序查询学生信息 SELECT * FROM students ORDER BY age ASC;
- 更新数据:
UPDATE students SET age = 23 WHERE name = '张三';
- 删除数据:
DELETE FROM students WHERE id = 1;
Oracle
- 创建数据库:创建数据库在Oracle中相对复杂,通常需要使用DBCA(Database Configuration Assistant)工具或者通过命令行执行一系列复杂的脚本,这里以创建表空间和用户来模拟创建数据库的部分操作:
```sql
-- 创建表空间
CREATE TABLESPACE my_tablespace
DATAFILE 'my_tablespace.dbf'
SIZE 100M
AUTOEXTEND ON;
-- 创建用户并指定表空间
CREATE USER my_user
IDENTIFIED BY my_password
DEFAULT TABLESPACE my_tablespace;
-- 给用户授予权限
GRANT CONNECT, RESOURCE TO my_user;
- **创建表**:
```sql
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(50) NOT NULL,
emp_age NUMBER,
emp_gender CHAR(1) CHECK (emp_gender IN ('M', 'F'))
);
- 插入数据:
INSERT INTO employees (emp_id, emp_name, emp_age, emp_gender) VALUES (1, 'John', 30, 'M'); INSERT INTO employees (emp_id, emp_name, emp_age, emp_gender) VALUES (2, 'Alice', 25, 'F');
- 查询数据:
-- 查询所有员工信息 SELECT * FROM employees; -- 查询年龄小于30岁的员工姓名和年龄 SELECT emp_name, emp_age FROM employees WHERE emp_age < 30; -- 按照员工年龄降序查询员工信息 SELECT * FROM employees ORDER BY emp_age DESC;
- 更新数据:
UPDATE employees SET emp_age = 32 WHERE emp_name = 'John';
- 删除数据:
DELETE FROM employees WHERE emp_id = 1;
SQL Server
- 创建数据库:
CREATE DATABASE my_database;
- 使用数据库:
USE my_database;
- 创建表:
CREATE TABLE customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(50) NOT NULL, customer_age INT, customer_gender CHAR(1) CHECK (customer_gender IN ('M', 'F')) );
- 插入数据:
INSERT INTO customers (customer_id, customer_name, customer_age, customer_gender) VALUES (1, 'Tom', 28, 'M'); INSERT INTO customers (customer_id, customer_name, customer_age, customer_gender) VALUES (2, 'Lucy', 26, 'F');
- 查询数据:
-- 查询所有客户信息 SELECT * FROM customers; -- 查询年龄在25到30岁之间的客户姓名和年龄 SELECT customer_name, customer_age FROM customers WHERE customer_age BETWEEN 25 AND 30; -- 按照客户姓名升序查询客户信息 SELECT * FROM customers ORDER BY customer_name ASC;
- 更新数据:
UPDATE customers SET customer_age = 29 WHERE customer_name = 'Tom';
- 删除数据:
DELETE FROM customers WHERE customer_id = 1;
以上只是一些常见的数据库操作语句示例,不同的数据库系统在语法和功能上可能会有一些差异。在实际使用中,还需要根据具体的需求和数据库的特性进行更复杂和灵活的操作。