JDBC连接MySql数据库

世上唯一不能复制的是时间,唯一不能重演的是人生,唯一不劳而获的是年龄。该怎么走,过什么样的生活,全凭自己的选择和努力。人生很贵,请别浪费!与智者为伍,与良善者同行。JDBC连接MySql数据库,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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();

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/260314.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!