1. MySQL
1.1 数据库操作: database
- 创建数据库:
- create database 数据库名
- create database 数据库名 character set 字符集
- 查看数据库:
- show database 查看数据库服务器中所有的数据库
- 删除数据库
- drop database 数据库名称
- 切换数据库
- use 数据库名
- select database() 查看正在使用的数据库
命令行进入mysql:
管理员权限:net start mysql net stop mysql
mysql -hlocalhost -uroot -p回车
1.2 表操作: table
1.2.1 创建表
create table 表名(
字段名 类型(长度) [约束],
字段名 类型(长度) [约束],
字段名 类型(长度) [约束]
)
- 主键约束: primary key
- 唯一语速: unique
- 非空约束: not null
1.2.2 查看表
- show tables 查看数据库中所有表
- desc 表名 查看表结构
1.2.3 删除表
drop table 表名
1.2.4 修改表
- 添加一列: alter table 表名 add 字段名 类型(长度) [约束]
- 修改列的类型(长度、类型):alter table 表名 modify 要修改的字段名 类型(长度) [约束]
- 修改列的列名: alter table 表名 change 旧列名 新列名 类型(长度) [约束]
- 删除表的列:alter table 表名 drop 列名
- 修改表名: rename table 表名 to 新表名
- 修改表的字符集:alter table 表名 character set 编码
1.3 字段类型
- 插入记录: insert into 表名(列名1,列名2,列名3……) values(值1,值2,值3……)
- 修改表记录
- 不带条件的: update 表名 set 字段名=值, 字段名=值, 字段名=值……
- 带条件的:update 表名 set字段名=值, 字段名=值, 字段名=值…… where 条件
- 删除记录: delete from 表名 where 条件
查询操作:select [distinct] *| 列名,列名 from 表名 [where条件]
- 简单查询:
- 条件查询
排序
- select … order by 字段1 asc|desc, 字段2 asc|desc (asc 升序, desc降序)
- 聚合
- 分组操作: group by
- 查询总结:
- select 一般在的后面的内容都是要查询的字段
from 要查询到表
where
group by
having 分组后带有条件只能使用having
order by 它必须放到最后面
- select 一般在的后面的内容都是要查询的字段
2. JDBC
2.1 JDBC的开发步骤
- 注册驱动
- 获得连接
- url参数:
jdbc:mysql://localhost:3306/web06_1?userUnicode=true&characterENcoding=UTF8
- url参数:
- 获得语句执行者
- 执行Sql语句
- int executeUpdate; 执行 insert update delete 语句
- ResultSet executeQuery; 执行select语句
- boolean execute ; 执行select返回true,执行其他的语句返回false
- 处理结果
JDBC连接案例
public class TestSelect {
public static Connection getConnection() throws Exception{
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/web06_1", "root","12345678");
}
public void query() throws SQLException {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//获得连接
con = getConnection();
//获取语句执行者
stmt = con.createStatement();
String sql = "select * from user";
//执行语句
rs = stmt.executeQuery(sql);
while (rs.next()){
String username = rs.getString(1);
String password = rs.getString(2);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
//释放资源
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
}
}
}