idea简单操作MySQL数据库

MySQL数据库操作(idea)

需要的包

https://pan.baidu.com/s/10FenEdrOsiNaBXEl5j1zoA
提取码:puow
在这里插入图片描述
下面是spring仓库地址,可进去自行搜索下载:https://repo.spring.io/webapp/#/home

整体结构

这里我先把jar包放在web目录下,出现较多问题,建议放在与src源码同级的目录

在这里插入图片描述
这里建议右键点击lib文件夹,add as library…->project library->ok

配置文件

druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/student?useSSL=false&&allowPublicKeyRetrieval=true
username=root
password=
initialSize=5
maxActive=10
maxWait=3000
maxIdle=8
minIdle=3

第二行(student)是你的数据库名字,改成自己的;第四行数据库密码填你的数据库密码。

不使用配置文件操作(直接重新建立连接)

上面环境配置好了,下面是简单操作代码,直接在src文件夹里新建class,复制进去就可以运行。
jdbc1.java

package cn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class jdbc1 {
    public static void main(String[] args) throws Exception {
      Class.forName("com.mysql.cj.jdbc.Driver");

      Connection coon=  DriverManager.getConnection("jdbc:mysql://localhost:3306/cainiao","root","你的密码");

      String sql="update user set age=30 where id=1";
        Statement stst=coon.createStatement();
        int count=stst.executeUpdate(sql);
        System.out.println(count);

        stst.close();
        coon.close();

    }
}

成功运行,打印输出1
当然,这个忽略就好,对理解下面没啥帮助。

操作数据库(使用配置文件)

druid.java

package cn;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class druid {
    public static void main(String[] args) throws Exception {
        //导入包
        //定义配置文件
        Properties pro=new Properties();
        InputStream is= druid.class.getClassLoader().getResourceAsStream("druid.properties");
        pro.load(is);
        PreparedStatement pstmt=null;
        //获取连接对象
        DataSource ds= DruidDataSourceFactory.createDataSource(pro);
        //获取链接
        Connection conn= ds.getConnection();
        System.out.println(conn);
		/**
		 * 插入
		 */
        String sql="insert into shili values(null,?,?)";
        // String sql="insert into shili(name,salary) values(?,?)";
        pstmt=conn.prepareStatement(sql);
        pstmt.setString(1,"jdbc");
        pstmt.setString(2,"4321");
        int count= pstmt.executeUpdate();
        System.out.println(count+"插入成功");

        /**
         * 修改
         */
        String xsql="update shili set salary=? where id=?";
        pstmt=conn.prepareStatement(xsql);
        pstmt.setString(1,"10000");
        pstmt.setString(2,"2");
        int countx= pstmt.executeUpdate();
        System.out.println(countx+"修改成功");

        /**
         * 删除
         */
        String ssql="delete from shili  where id=?";
        pstmt=conn.prepareStatement(ssql);
        pstmt.setInt(1,3);
        int counts= pstmt.executeUpdate();
        System.out.println(counts+"删除成功");
        /**
         * 查询
         */
        String csql="select * from shili";
       // String sql="select * from shili where id=?";
        Statement smt = conn.createStatement();
        ResultSet rs = smt.executeQuery(csql);
        while (rs.next()) {
            int id= rs.getInt("id");
            int salary = rs.getInt("salary");
            String name = rs.getString("name");
            System.out.println(id+"  "+salary+"  "+name);
        }
        System.out.println("查询成功");
    }
}

直接在src文件夹里新建class,复制进去就可以运行。
运行结果:在这里插入图片描述
我的数据库截图:
在这里插入图片描述
当然,这样会存在一个问题,当项目大了,多个操作数据库的文件,每个文件里都重新创建一个连接,那还是程序员吗?

所以,听说过utils包吧,把上面代码里面的数据库创建连接及关闭连接提取出来放在工具包里,就这么简单。

使用工具类加配置文件操作

jdbcutils.java

package cn;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/*
连接池工具类
 */
public class jdbcutils {
    private static DataSource ds;

    static{
        Properties pro=new Properties();
        try {
            //加载配置文件
            pro.load(jdbcutils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取datasource
            ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    获取连接
     */
    public static Connection getconnection() throws SQLException {
        return ds.getConnection();
    }
    /*
    释放资源
     */
    public static  void close(Statement stmt, Connection conn){
        close(null,stmt,conn);
    }
    public static  void close(ResultSet rs, Statement stmt, Connection conn){
        if(rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /*
    获取连接池
     */
    public static DataSource getdatasource(){
        return ds;
    }
}

shili.java

package cn;

public class shili {
    private Integer id;
    private static String name;
    private Integer salary;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public static String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSalary() {
        return salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "shili{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                '}';
    }
}

jdbcutilTest.java

package cn;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;
public class jdbcutilsTest {
    public static void main(String[] args) {
    }
    JdbcTemplate templete =new JdbcTemplate(jdbcutils.getdatasource());
    @Test//修改
    public void test_xiugai(){
        //System.out.println("成功");
        String sql="update shili set salary=? where id =?";
        int count=templete.update(sql,2000,1);
        System.out.println(count);
    }
    @Test//添加
    public void test_tianjia(){
     String sql="insert into shili(name,salary) values(?,?)";
     int count=templete.update(sql,"wang","2000");
        System.out.println(count);
    }
    @Test//删除
    public void test_shanchu(){
        String sql="delete from shili where id=?";
        int count=templete.update(sql,9);
        System.out.println(count);
    }
    @Test//获取map集合,几乎不会使用
    public void test_fenzhuangMAP(){
        String sql="select * from shili where id=?";
        Map<String, Object> stringObjectMap = templete.queryForMap(sql,1);
        System.out.println(stringObjectMap);
    }
    @Test//获取list集合
    public void test_fenzhuangLIST(){
        String sql="select * from shili";
        List<Map<String, Object>> list = templete.queryForList(sql);
        for(Map<String,Object> stringObjectMap:list) {
            System.out.println(stringObjectMap);
        }
    }
    @Test//获取javabean集合
    public void test_fenzhuangBEAN(){
        String sql="select * from shili";
        List<shili> list = templete.query(sql, new BeanPropertyRowMapper<shili>(shili.class));
        for(shili shili:list) {
            System.out.println(shili);
        }
        Integer id=list.get(0).getId();
        System.out.println(id);
    }
    @Test//查询总记录数
    public void test_chaxunjilushu(){
        String sql="select count(id) from shili";
        Long aLong = templete.queryForObject(sql, Long.class);
        System.out.println(aLong);

    }
}

over

运行结果自己看吧,我就不贴截图了。
至于我用的数据库嘛,就是上面截图那样,自行创建吧。
如果你还不知道项目里面文件夹怎么放的:我的就长这样,你想让他好看点儿就自己加包吧
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello-o

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值