第十八天,开始涉及到数据库相关的内容
18周 JAVA从入门到入土
一、数据库
用文本保存数据,增删改查工作十分麻烦,所以需要使用数据库来存储数据。
1.1 基础命令
查:select * from tb;
增:insert into tb(col1,col2,col3,…) values(val1,val2,val3,…);
改:update tb set col1=val1 and col2=val2;
删:delete from tb;
1.2 where子句
where 子句是用来定位某一些具体数据的,如果需要定位到唯一值,一般定位主键。
where 的几种用法:
where col1=val1 and/or col2=val2;
where col>val/col<val;
where col like ‘%keyword%’;
where col in(val1,val2,val3,…);
where col between val1 and val2;
二、JDBC
2.1 数据库源四要素
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://127.0.0.1:3306/数据库名
user:账户
password:密码
2.2 java连入数据库
Class.forName(driver);
Connection con = DriverManager.getConnection(url, user, pass);
Statement state = connect.createStatement();
ResultSet resultSet = pState.execute(sql);
con.close();
2.3 SQL注入
java 程序在拼接 SQL 语句的时候,会因为一些恶意的拼接,导致数据库的数据错误。这时可以通过 ?占符 来解决这个问题。
在 SQL 语句中用 ? 字符占据原来数据的位置。
Class.forName(driver);
Connection con = DriverManager.getConnection(url, user, pass);
PreparedStatement pState = con.prepareStatement(sql);
pState.setInt(1, 值);
pState.setString(2, "值");
pState.setObject(3, ...);
...
ResultSet resultSet = pState.execute();
con.close();