连接数据库
注意:不同的JDK版本要使用对应版本的 jdbc的jar包
//注册驱动动-反射去加载jar包中com.mysgl.jdbc.Driver这个类中的 DriverManager.registerDriver(new Driver()):
Class.forName("com.mysql.cj.jdbc.Driver");
//url 表示和数据库通信的地址
//如果url中需要带参数,则需要使用?进行连接
//如果需要多个参数,从第二个参数开始使用&连接
String url = "jdbc:mysql://localhost:3306/jdbc";
//jdbc:mysql://localhost:3306/fruitdb?useSSL=false&characterEncoding=utf-8
//3306/jdbc 的jdbc是连接数据库的名字
//useSSL=false 通过账号密码进行连接
//characterEncoding=utf-8这一段是java传进mysql里时编码的设置,
String user = "root"; //自己数据库的用户
String password = "123456"; //自己数据库的密码
Connection conn = DriverManager.getConnection(url,user,password);
读取数据库中存储的数据
String sql = "select * from user";
Statement stmt = conn.createStatement(); //获得一个 Statement 对象
ResultSet rs = stmt.executeQuery(sql);
Statement
是用来执行SQL语句的 有两个常用方法executeUpdate
用于 增加 删除 修改语句executeQuery
用于查询语句
ResultSet
用来存储 查询语句 的结果
取出查询的结果
while (rs.next()){ 读取结果集的光标向下移动一行,光标默认所在列名哪一行(第0行) 刚好这个方法返回的是boolean类型 有数据返回Ture 没数据返回false
int id = rs.getInt(1); //数据库第一列 是id 格式是int
String name = rs.getString(2); //数据库第二列是姓名 格式是String
String pw = rs.getString(3); //也可以写数据库的列名
String email = rs.getString(4);
String date = rs.getString(5);
System.out.println(id + "\t\t\t" + name + "\t\t\t" + pw + "\t\t\t" + email + "\t\t\t" + date);
}
- 取的什么格式 rs.getXX XX就是什么格式 跟数据库存储的数据类型匹配
String sql1 = "INSERT INTO user(id,name,password,email,birthday) VALUES(?,?,?,?,?)";
PreparedStatement ppst = conn.prepareStatement(sql1);
- PreparedStatement 预编译SQL并执行SQL
ArrayList<User> lis = new ArrayList<>();
lis.add(user);
lis.add(user1);
lis.add(user2);
PreparedStatement pre = conn.prepareStatement(sql1);
Iterator<User> it = lis.iterator();
while(it.hasNext()){
User next1 = it.next(); //这里的数字s
pre.setInt(1, next1.getId());
pre.setString(2, next1.getName());
pre.setString(3, next1.getPassword());
pre.setString(4, next1.getEmail());
pre.setString(5, next1.getBirthday());
pre.execute(); //执行预编译SQL
}
psmt.executeUpdate() //这个也是执行预编译sql语句 常用在return 返回值插入成功返回true
//**当成功插入数据到数据库时候,这个会返回一个大于1的数字,来表明数据成功插入库之中**