一、Java连接数据库
1.加载JDBC-Mysql数据库连接器(应提前下载数据连接器及对应的Mysql数据库驱动)
try{Class.forName("com.mysql.cj.jdbc.Driver");
}
catch(Exception e){}
2.创建对象(con、sql、rs)
con | 连接对象,用于连接数据库 |
sql | sql语句对象,用于查询 |
rs | 返回结果对象,查询返回值 |
Connetion con=null;
Statement sql;
ResultSet rs;
3.使用con对象连接数据库
String uri = "hdbc:mysql://localhost:3306/数据库名?+
"useSS L= false&serverTimezone = CST&characterEncoding=utf-8";
String user="用户名";
Srting paassword="密码";
try{
con = DriverManager.getConnection(uti,user,password);
}
catch(SQLException e){
System.out.println(e);
}
4.使用sql对象,编写sql语句,进行查询
sql= con.createStatement(); //使用con连接对象的createStatement()方法创建SQL语句对象
rs=sql.executeQuery("SELECT * FROM 数据库名");
5.处理查询结果
rs是ResultSet类声明的对象,按“列”组织的数据行构成 ;
例如:ResultSet rs = sql.executeQuery("SELECT * FROM booklist");
rs获得的是列组成的数据行
使用next()方法能读取到下一行数据,使用getXxx()方法能获取对应的值
eg:
while(rs.next()){
String number = rs.getString(1);
String name = rs.getString(2);
float price = rs.getFloat(3);
Date date = rs.getDate(4);
System.out.printf("%s,%s,%.2f,%s",number,name,price,date);
}
//其中getXxx中的数字表示获取第几列中的值
6.使用完数据库及时关闭连接
con.close;
二、Java按条件查找或进行排序
条件查找语句结构:select 字段 from 表名 where 条件
条件:某值=“ ”、X属于某个范围、使用like进行模式匹配 ,使用%代替0个或多个字符,用下划线表示一个字符(例如查询booklist中name中含有"我"的书名:selcet name from booklist where name like "%我%")
排序语句结构:select * from 表名 by 列名
(默认从小到大)select * from 表名 where 条件 order by 列名
综合应用:
查询booklist中价格大于30,出版年份在1999~2021年的图书,按照price排序
public static void main(String args[]){
Connection con;
Statement sql;
ResultSet rs;
con = GetDBConnection.connectDB("Book","root","");
String SQL="select * from bookist" + //查询对象
"where year between 1999 and 2021 and price >=30" + //查询条件
"order by price"; //排序条件
if(con == null) return;
try{
sql = con.creatStatement();
rs = sql.excuteQuery(SQL);
while(rs.next()){
String ISBN = rs.getString(1);
String name = rs.getString(2);
String price = rs.getString(3);
String date = rs.getString(4);
System.out.printf("%s,%s,%f,%s",ISBN,name,price,date);
}
con.close();
}
catch(SQLException e){}
}
三、对数据库执行更新、添加或删除操作
更新语句结构:update 表 set 字段 = 新值 where <条件子句>
添加语句结构:insert into 表(字段列表)values (对应的具体记录)
删除语句结构:delete from 表名 where <条件子句>
使用 sql对象的executeUpdate(sql语句)完成对数据库的操作
......
//创建con、sql、rs对象
//连接数据库
String upddateRecord = "update booklist set chuban-time = '2021-04-09' where name = '牛客基础编程题'";-
String record = "('2-306-08465-7','春天','35.8','2020-02-27'),"+
"('5-777-56462-9','冬天','29.9','2020-05-07')";
String addRecord = "insert into booklist values"+record;
try{
...
int ok = sql.excuteUpdate(addRecord); //添加两条记录
ok = sql.executeUpdate(updateRecord); //更新一条记录
rs = sql.excuteQuery("select * from booklist"); //对结果进行查询
...
}
四、使用预处理语句(使用PreparedStatement对象)