JDBC连接MySql数据库

1.静态加载Driver

static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

2.创建连接

 private static Connection getConnection(){
        try {
            return DriverManager.getConnection("url","root","pwd");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
}

3 简单操作

Connection connection = getConnection();
System.out.printf("数据库是否连接成功:%b \n",!connection.isClosed());
//查询
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select name, account from tb_user where is_deleted = 0 limit 0,10");
boolean next = resultSet.next();
System.out.println(String.format("是否在第一行:%s", next));
List<Map> mapList=new ArrayList<>();
while (resultSet.next()){
    String name = resultSet.getString("name");
    String account = resultSet.getString("account");
    Map map=new HashMap();
    map.put("name",name);
    map.put("account",account);
    mapList.add(map);
}
mapList.forEach(System.out::println);
//添加
boolean execute = statement.execute("insert into tb_user (name,account,email) value ('小米','xiaomi@xiaomi.com','xiaomi@xiaomi.com')");
System.out.printf("是否添加成功 %b \n",!execute);
//更新
int update = statement.executeUpdate("update tb_user set name ='大明' where id= 48");
System.out.printf("更新数量 %s \n",update);
//删除
int delete = statement.executeUpdate("delete from tb_user  where id= 49");
System.out.printf("删除数量 %s \n",delete);
statement.close();

//防止SQL注入
//添加
PreparedStatement insertPreparedStatement = connection.prepareStatement("insert into tb_user (name,account,email) " +
       "value (?,?,?)");
insertPreparedStatement.setString(1,"小红");
insertPreparedStatement.setString(2,"xiaohong@xiaohong.com");
insertPreparedStatement.setString(3,"xiaohong@xiaohong.com");
boolean insert = insertPreparedStatement.execute();
insertPreparedStatement.close();
System.out.printf("防止sql注入 执行是否成功 %b \n",!insert);
//查询
PreparedStatement preparedStatement = connection.prepareStatement("select name, account from tb_user where is_deleted = 0 limit 0,10");
ResultSet executeQuery = preparedStatement.executeQuery();
while (executeQuery.next()){
   String name = executeQuery.getString("name");
   String account = executeQuery.getString("account");
   System.out.printf("name: %s,account:%s \n",name,account);
}
preparedStatement.close();
connection.prepareStatement("sql");
connection.close();
connection.close();
posted @ 2022-09-26 16:11  sowler  阅读(15)  评论(0编辑  收藏  举报  来源