1. 注册过程
以下是简单的输出表所有数据过程,需要先在MySQL创建表,这里表名是user
这里的url后半部分暂时不了解,先这样写:
“jdbc:mysql://localhost:3306/myjdbc?useUnicode- true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF-8”
static void test() throws Exception{
//1.驱动管理器,注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//2.建立连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc?useUnicode-true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF-8"
,"root","root");
//3.创建语句,发起请求
Statement st = conn.createStatement();
//4.执行语句,结果集
ResultSet rs = st.executeQuery("select * from user");
//5.处理结果
while(rs.next()){
System.out.println(rs.getInt(1) +","+rs.getString(2)+","
+rs.getString(3)+","+rs.getInt(4));
}
rs.close();
st.close();
conn.close();
}
关闭顺序与打开顺序相反
先关闭结果集 ResultSet 然后关闭 Statement 最后关闭连接 Connection
结果集的getInt()方法接受一个参数 相当于表的列数 第一列是id,就调用getInt();第二个是username,是String类型 ,就调用getString();
2. 增删改的实现
增:
static void insert(String username,String password){
Connection conn = null;
PreparedStatement pst = null;
try{
String sql = "insert into user(username,password) values(?,?)";
//建立连接
...
if(conn == null)
throw new NullPointerException();
/*Statement.RETURN_GENERATED_KEYS用于获取更新的id的方法的实现,没有就不能调用 getGeneratedKeys();*/
pst = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pst.setString(1,username);
pst.setString(2,password);
pst.executeUpdate();
ResultSet rs = pst.getGeneratedKeys();
if(rs.next())//不进行判断会报错
System.out.println("id " + rs.getInt(1));
}catch (Exception e){
e.printStackTrace();
}
}
这边用PreparedStatement代替Statement,可以防止SQL注入
SQL注入
使用Statement时,直接给Statement传入sql语句,可能
String sql = “select * from user where id = 1”;
但是如果把SQL改成 “select * from user where id = 1 or 1 = 1”,这句话将查找所有数据
再看一个,完全把密码输入为 1 ' or '1 = 1
sql就变成 select * from user where username = ‘xxx’ and password = ‘1’ or ‘1 = 1’;
这样即使不知道密码也能查到信息了
static boolean selectByUP(String username,String password){
...
String sql = "select * from user where username ='"+username + "' and password ='" + password +"';";
rs = st.executeQuery(sql);
...
}
}
现在看插入操作,建立PreparedStatement后给" ?"设置值(从1开始) pst.setString(1,username);这样就会自动生成SQL语句,更加安全,其他PreparedStatement的好处以后再说;
删除操作
static void delete(int id){
Connection conn = null;
PreparedStatement pst = null;
try{
String sql = "delete from user where id = ?";
//建立连接
...
if(conn == null)
throw new NullPointerException();
pst = conn.prepareStatement(sql);
pst.setInt(1,id);
int result = pst.executeUpdate();
if(result == 1){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
}catch (Exception e){
e.printStackTrace();
}
}
修改操作
static void updatePassword(int id, String newPassword){
Connection conn = null;
PreparedStatement pst = null;
try{
String sql = "update user set password = ? where id = ?";
//建立连接
...
if(conn == null)
throw new NullPointerException();
pst = conn.prepareStatement(sql);
pst.setString(1,newPassword);
pst.setInt(2,id);
int result = pst.executeUpdate();
if(result == 1){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
}catch (Exception e){
e.printStackTrace();
}
}
3.查询
static boolean selectByUP2(String username,String password){
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
conn = JdbcUtils.getConnection();
if(conn==null){
throw new NullPointerException();
}
//查询
pst = conn.prepareStatement("select * from user where usename = ? and password = ?");
pst.setString(1,username);
pst.setString(2,password);
rs = pst.executeQuery();
return rs.next();
}catch (Exception e){
e.printStackTrace();
return false;
}finally {
JdbcUtils.close(rs,pst,conn);
}
}
在使用preparedStatement时,会有execute 和executeUpdate两个方法,还有executeQuery方法(百度了解,遛~)
3.事务
A给B转帐200,在转帐过程中,A的钱减少200,但如果B的钱还没增加时数据库出现了故障,可能出问题,解决办法是Connection的setAutoCommit(false);
和conn.commit();
将整个转帐过程写在setAutoCommit(false);之后,转帐完成后在调用提交commit方法,数据才会发生改变,如果中间出现故障,那么事务就不会发生,两者的钱就不会改变。
static void changeMoney(String username1,String username2,int money){
Connection conn = null;
PreparedStatement pst = null;
try{
String sql = "update user set money = money - ? where usename = ?";
conn = JdbcUtils.getConnection();
if(conn == null)
throw new NullPointerException();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
pst.setInt(1,money);
pst.setString(2,username1);
int result1 = pst.executeUpdate();
pst.setInt(1,-money);
pst.setString(2,username2);
int result2 = pst.executeUpdate();
if(result1==1&&result2==1)
conn.commit();
}catch (Exception e){
e.printStackTrace();
}
}
(未完待续)