JDBC学习笔记

JDBC的学习笔记,主要包括内容有

  • MySQL配置和语法笔记
  • JDBC语法和实例
  • DAO设计模式

MySQL配置

https://www.cnblogs.com/laumians-notes/p/9069498.html

MySQL语法

https://www.cnblogs.com/mr-wid/archive/2013/05/09/3068229.html#c2

https://www.yiibai.com/jdbc/jdbc-sql-syntax.html#article-start

结构化查询语言(SQL)是一种标准化语言,允许对数据库执行操作,例如:创建数据记录,读取内容,更新内容和删除数据记录等。

本教程中将概述SQL,这是了解和学习JDBC概念的前提条件。 经过本章后,您将能够在数据库中创建,创建,读取,更新和删除(通常称为CRUD操作)数据。

有关SQL的详细了解,可以阅读我们的MySQL教程

1. 创建数据库

CREATE DATABASE语句用于创建新的数据库。 语法是 -

SQL> CREATE DATABASE DATABASE_NAME;
SQL

示例
以下SQL语句创建一个名为EMP的数据库 -

SQL> CREATE DATABASE EMP;
SQL

2. 删除数据库

DROP DATABASE语句用于删除存在的数据库。 语法是 -

注意:要创建或删除数据库,需要有数据库服务器的管理员权限。 需要特别小心的是:删除数据库将丢失数据库中存储的所有数据(无法恢复)。

3. 创建表

CREATE TABLE语句用于创建新表。 语法是 -

SQL> CREATE TABLE table_name
(
   column_name column_data_type,
   column_name column_data_type,
   column_name column_data_type
   ...
);
SQL

示例

以下SQL语句创建一个名为Employees的表,其中包含四列:

SQL> CREATE TABLE Employees
(
   id INT NOT NULL,
   age INT NOT NULL,
   first VARCHAR(255),
   last VARCHAR(255),
   PRIMARY KEY ( id )
);
SQL

4. 删除表

DROP TABLE语句用于删除存在的表。 语法是 -

SQL> DROP TABLE table_name;
SQL

示例

以下SQL语句删除名为Employees的表 -

SQL> DROP TABLE Employees;
SQL

5. INSERT数据

INSERT的语法如下所示,其中column1column2等表示要显示在相应列中的数据值 -

SQL> INSERT INTO table_name VALUES (column1, column2, ...);
SQL

示例

以下SQL INSERT语句在先前创建的Employees表中插入一个新行 -

SQL> INSERT INTO Employees VALUES (100, 18, 'Max', 'Su');
SQL

6. 查询数据

SELECT语句用于从数据库检索数据。 SELECT的语法是 -

SQL> SELECT column_name, column_name, ...
     FROM table_name
     WHERE conditions;
SQL

WHERE子句可以使用比较运算符,例如:=!=<><=>=,以及BETWEENLIKE运算符。

示例

以下SQL语句从Employees表中选择:agefirstlast列,其中id列为100 -

SQL> SELECT first, last, age 
     FROM Employees 
     WHERE id = 100;
SQL

以下SQL语句从Employees表中选择:age, firstlast 列,其中first列包含Max -

SQL> SELECT first, last, age 
     FROM Employees 
     WHERE first LIKE '%Max%';
SQL

7. 更新数据

UPDATE语句用于更新数据。 UPDATE的语法是 -

SQL> UPDATE table_name
     SET column_name = value, column_name = value, ...
     WHERE conditions;
SQL

WHERE子句可以使用比较运算符,例如:=!=<><=>=,以及BETWEENLIKE运算符。

示例

以下SQL UPDATE语句更新id100的雇员的age列的值为:20

SQL> UPDATE Employees SET age=20 WHERE id=100;
SQL

8. 删除数据

DELETE语句用于从表中删除数据。 DELETE的语法是 -

SQL> DELETE FROM table_name WHERE conditions;
SQL

WHERE子句可以使用比较运算符,例如:=!=<><=>=,以及BETWEENLIKE运算符。

示例

以下SQL DELETE语句将删除ID100的员工的记录 -

SQL> DELETE FROM Employees WHERE id=100;
select * from emp;  #注释
#---------------------------
#----命令行连接MySql---------
 
#启动mysql服务器
net start mysql
 
#关闭 
net stop mysql
  
#进入
mysql -h 主机地址 -u 用户名 -p 用户密码
 
#退出
exitstatus;显示当前mysql的version的各种信息。
 
#---------------------------
#----MySql用户管理---------
 
#修改密码:首先在DOS 下进入mysql安装路径的bin目录下,然后键入以下命令:
mysqladmin -uroot -p123 password 456;
 
#增加用户
#格式:grant 权限 on 数据库.* to 用户名@登录主机 identified by '密码'
/*
如,增加一个用户user1密码为password1,让其可以在本机上登录, 并对所有数据库有查询、插入、修改、删除的权限。首先用以root用户连入mysql,然后键入以下命令:
grant select,insert,update,delete on *.* to user1@localhost Identified by "password1";
如果希望该用户能够在任何机器上登陆mysql,则将localhost改为"%"。
如果你不想user1有密码,可以再打一个命令将密码去掉。
grant select,insert,update,delete on mydb.* to user1@localhost identified by "";
*/
 
grant all privileges on wpj1105.* to sunxiao@localhost identified by '123';   #all privileges 所有权限
 
#----------------------------
#-----MySql数据库操作基础-----
 
#显示数据库
show databases;
 
#判断是否存在数据库wpj1105,有的话先删除
drop database if exists wpj1105;
 
#创建数据库
create database wpj1105;
 
#删除数据库
drop database wpj1105;
 
#使用该数据库
use wpj1105;
 
#显示数据库中的表
show tables;
 
#先判断表是否存在,存在先删除
drop table if exists student;
 
#创建表
create table student(
id int auto_increment primary key,
name varchar(50),
sex varchar(20),
date varchar(50),
content varchar(100)
)default charset=utf8;
 
#删除表
drop table student;
 
#查看表的结构
describe student;  #可以简写为desc student;
 
#插入数据
insert into student values(null,'aa','男','1988-10-2','......');
insert into student values(null,'bb','女','1889-03-6','......');
insert into student values(null,'cc','男','1889-08-8','......');
insert into student values(null,'dd','女','1889-12-8','......');
insert into student values(null,'ee','女','1889-09-6','......');
insert into student values(null,'ff','null','1889-09-6','......');
#查询表中的数据
select * from student;
select id,name from student;
 
#修改某一条数据
update student set sex='男' where id=4;
 
#删除数据
delete from student where id=5;
 
# and 且
select * from student where date>'1988-1-2' and date<'1988-12-1';
 
# or 或
select * from student where date<'1988-11-2' or date>'1988-12-1';
  
#between
select * from student where date between '1988-1-2' and '1988-12-1';
 
#in 查询制定集合内的数据
select * from student where id in (1,3,5);
 
#排序 asc 升序  desc 降序
select * from student order by id asc;
 
#分组查询 #聚合函数
select max(id),name,sex from student group by sex;
 
select min(date) from student;
 
select avg(id) as '求平均' from student;
 
select count(*) from student;   #统计表中总数
 
select count(sex) from student;   #统计表中性别总数  若有一条数据中sex为空的话,就不予以统计~
 
select sum(id) from student;
 
#查询第i条以后到第j条的数据(不包括第i条)
select * from student limit 2,5;  #显示3-5条数据
 
#巩固练习
create table c(
 id int primary key auto_increment,
 name varchar(10) not null,
 sex varchar(50) ,  #DEFAULT '男' ,
 age int unsigned, #不能为负值(如为负值 则默认为0)
 sno int unique    #不可重复
);
 
drop table c;
desc c;
 
insert into c (id,name,sex,age,sno) values (null,'涛哥','男',68,1);
insert into c (id,name,sex,age,sno) values (null,'aa','男',68,2);
insert into c (id,name,sex,age,sno) values (null,'平平','男',35,3);
...
 
select * from c;
 
#修改数据
update c set age=66 where id=2;
update c set name='花花',age=21,sex='女' where id=2
delete from c where age=21;
 
#常用查询语句
select name,age ,id from c
select * from c where age>40 and age<60;  #and
select * from c where age<40 or age<60;  #or
select * from c where age between 40 and 60 #between
select * from c where age in (30,48,68,99);     #in 查询指定集合内的数据
select * from c order by age desc;      #order by (asc升序 des降序)
 
#分组查询
select name,max(age) from c group by sex;  #按性别分组查年龄最大值
#聚合函数
select min(age) from c;
select avg(age) as '平均年龄 ' from c;
select count(*) from c;  #统计表中数据总数
select sum(age) from c;
 
#修改表的名字
#格式:alter table tbl_name rename to new_name
alter table c rename to a;
  
#表结构修改
create table test
(
id int not null auto_increment primary key, #设定主键
name varchar(20) not null default 'NoName', #设定默认值
department_id int not null,
position_id int not null,
unique (department_id,position_id) #设定唯一值
);
 
#修改表的名字
#格式:alter table tbl_name rename to new_name
alter table test rename to test_rename;
 
#向表中增加一个字段(列)
#格式:alter table tablename add columnname type;/alter table tablename add(columnname type);
alter table test add  columnname varchar(20);
 
#修改表中某个字段的名字
alter table tablename change columnname newcolumnname type;  #修改一个表的字段名
alter table test change name uname varchar(50);
 
select * from test;
 
#表position 增加列test
alter table position add(test char(10));
#表position 修改列test
alter table position modify test char(20) not null;
#表position 修改列test 默认值
alter table position alter test set default 'system';
#表position 去掉test 默认值
alter table position alter test drop default;
#表position 去掉列test
alter table position drop column test;
#表depart_pos 删除主键
alter table depart_pos drop primary key;
#表depart_pos 增加主键
alter table depart_pos add primary key PK_depart_pos
(department_id,position_id);
 
#用文本方式将数据装入数据库表中(例如D:/mysql.txt)
load data local infile "D:/mysql.txt" into table MYTABLE;
 
#导入.sql文件命令(例如D:/mysql.sql)
source d:/mysql.sql;  #或者  /. d:/mysql.sql;

JDBC数据库连接

https://www.yiibai.com/jdbc/jdbc-db-connections.html#article-start

使用JDBC驱动程序连接MySQL数据库的示例代码片段 -

Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/db_name","db_username", "db_password");
conn.close();

Statements, PreparedStatement和CallableStatement

Statement对象

1.1 创建Statement对象

在使用Statement对象执行SQL语句之前,需要使用Connection对象的createStatement()方法创建一个Statement对象,如以下示例所示:

Statement stmt = null;
try {
   stmt = conn.createStatement( );
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}
Java

在创建Statement对象后,可以使用它来执行一个SQL语句,它有三个执行方法可以执行。它们分别是 -

  • boolean execute (String SQL) : 如果可以检索到ResultSet对象,则返回一个布尔值true; 否则返回false。使用此方法执行SQLDDL语句或需要使用真正的动态SQL,可使用于执行创建数据库,创建表的SQL语句等等。
  • int executeUpdate (String SQL): 返回受SQL语句执行影响的行数。使用此方法执行预期会影响多行的SQL语句,例如:INSERTUPDATEDELETE语句。
  • ResultSet executeQuery(String SQL):返回一个ResultSet对象。 当您希望获得结果集时,请使用此方法,就像使用SELECT语句一样。

1.2. 关闭Statement对象

就像关闭一个Connection对象一样,以保存数据库资源一样,由于同样的原因,还应该关闭Statement对象。

一个简单的调用close()方法将执行该作业(工作)。 如果先关闭Connection对象,它也会关闭Statement对象。 但是,应该始终显式关闭Statement对象,以确保正确的清理顺序。

Statement stmt = null;
try {
   stmt = conn.createStatement( );
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   stmt.close();
}
Java 

PreparedStatement对象

PreparedStatement接口扩展了Statement接口,它添加了比Statement对象更好一些优点的功能。

此语句可以动态地提供/接受参数。

2.1 创建PreparedStatement对象

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}
Java

JDBC中的所有参数都由 ? 符号作为占位符,这被称为参数标记。 在执行SQL语句之前,必须为每个参数(占位符)提供值。

setXXX()方法将值绑定到参数,其中XXX表示要绑定到输入参数的值的Java数据类型。 如果忘记提供绑定值,则将会抛出一个SQLException

每个参数标记是它其顺序位置引用。第一个标记表示位置1,下一个位置2等等。 该方法与Java数组索引不同(它不从0开始)。

所有Statement对象与数据库交互的方法(a)execute(),(b)executeQuery()和(c)executeUpdate()也可以用于PreparedStatement对象。 但是,这些方法被修改为可以使用输入参数的SQL语句。

2.2. 关闭PreparedStatement对象

就像关闭Statement对象一样,由于同样的原因(节省数据库系统资源),也应该关闭PreparedStatement对象。

简单的调用close()方法将执行关闭。 如果先关闭Connection对象,它也会关闭PreparedStatement对象。 但是,应该始终显式关闭PreparedStatement对象,以确保以正确顺序清理资源。

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   pstmt.close();
}
Java

结果集ResultSet

浏览结果集

ResultSet接口中有几种涉及移动光标的方法,包括 -

编号 方法 描述
1 public void beforeFirst() throws SQLException 将光标移动到第一行之前
2 public void afterLast() throws SQLException 将光标移动到最后一行之后。
3 public boolean first() throws SQLException 将光标移动到第一行。
4 public void last() throws SQLException 将光标移动到最后一行。
5 public boolean absolute(int row) throws SQLException 将光标移动到指定的行。
6 public boolean relative(int row) throws SQLException 从当前指向的位置,将光标向前或向后移动给定行数。
7 public boolean previous() throws SQLException 将光标移动到上一行。 如果上一行关闭结果集,此方法返回false
8 public boolean next() throws SQLException 将光标移动到下一行。 如果结果集中没有更多行,则此方法返回false
9 public int getRow() throws SQLException 返回光标指向的行号。
10 public void moveToInsertRow() throws SQLException 将光标移动到结果集中的特殊行,该行可用于将新行插入数据库。当前光标位置被记住。
11 public void moveToCurrentRow() throws SQLException 如果光标当前位于插入行,则将光标移回当前行; 否则,此方法什么也不做

查看结果集

ResultSet接口包含数十种获取当前行数据的方法。

每个可能的数据类型都有一个get方法,每个get方法有两个版本 -

  • 一个是采用列名称。
  • 另一个采用列索引。

例如,如果对查看感兴趣的列包含一个int,则需要使用ResultSet的其中一个getInt()方法 -

序号 方法 描述
1 public int getInt(String columnName) throws SQLException 返回名为columnName的列中当前行中的int值。
2 public int getInt(int columnIndex) throws SQLException 返回指定列索引当前行中的int值。列索引从1开始,意味着行的第一列为1,行的第二列为2,依此类推。

类似地,在八个Java基元类型中的每一个的ResultSet接口中都有get方法,以及常见的类型,如java.lang.Stringjava.lang.Objectjava.net.URL等。

还有一些方法可以获取SQL数据类型java.sql.Date,java.sql.Timejava.sql.TimeStampjava.sql.Clobjava.sql.Blob。查看文档以获取有关使用这些SQL数据类型的更多信息。

DAO设计模式

例子:https://blog.csdn.net/dingse/article/details/78383323

原文地址:https://www.cnblogs.com/cpaulyz/p/12401099.html