Java通过JDBC连接数据库的三种方式!!!并对数据库实现增删改查

前言
java连接数据库完整流程为:
1,获得驱动(driver),数据库连接(url),用户名(username),密码(password)基本信息的三种方式。
2,通过获得的信息完成JDBC实现连接数据库。
注:连接前请导入jar包,例:连接mysql数据库需要导入mysql-connector-java-5.1.39-bin.jar包


连接数据库的三种方式

三种方式中二,三最为常用

一,直接获取数据库信息,并jdbc驱动连接

这里写代码片  public static Connection connection() {
        //获得连接数据库连接
        Connection conn=null;
        try {
        //初始化Driver类,注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //连接数据库
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/web", "root", "root");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn; 
    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

二,获得db.properties文件中的配置信息获得

注解:
ResourceBundle 类的作用就是读取资源属性文件(properties),根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。

public class Jdbc_Conn2 {
      private static String driver;
      private static String url;
      private static String username;
      private static String password;
      static {
          //通过ResourceBundle获得db文件中的信息
          ResourceBundle bundle = ResourceBundle.getBundle("db");
          //通过key值获得db文件中的配置信息
          driver=bundle.getString(driver);
          url=bundle.getString(url);
          username=bundle.getString(username);
          password=bundle.getString(password);
      }

    public static Connection mysqlconn() {
        //连接数据库
        Connection conn=null;
            Class.forName(driver);
            conn= DriverManager.getConnection(url, username, password);
            return conn; 
    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

三、通过IO流获得db文件中配置信息

注解:
*首先,调用对象的getClass()方法是获得对象当前的类类型,这部分数据存在方法区中,而后在类类型上调用getClassLoader()方法是得到当前类型的类加载器,在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就是保证是和类类型同一个加载器加载的。
最后调用了类加载器的getResourceAsStream()方法来加载文件资源*

public class Jdbc_Conn3 {
    private static String dirver;
    private static String url;
    private static String username;
    private static String password;
    static {
    //IO流
        InputStream is=Jdbc_Conn3.class.getClassLoader().getResourceAsStream("db.properties");
        Properties props=new Properties();
        try {
            props.load(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dirver=props.getProperty("driver");
        url=props.getProperty("url");
        username=props.getProperty("username");
        password=props.getProperty("password");
    }


    public static Connection mysqlconn() {
        //1,获得连接数据库的驱动
        Connection conn=null;
        Class.forName(dirver);
        conn= DriverManager.getConnection(url, username, password);
        return conn; 
    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

连数据库后,使用完毕需要关闭连接

关闭数据库需要关闭以下资源:1,Connection(连接).2,PreparedStatement(预编译).3,Result(结果集)

    public static void mysqlcolse(Connection con,PreparedStatement pstem,ResultSet rs) {

            try {
                if(con!=null) {
                con.close();
                }
                if(pstem!=null)
                {
                    pstem.close();
                }
                if(rs!=null) {
                    rs.close();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

完成以上步骤便是一个连接数据库的java模板了,以上连接方法与关闭方法存于一个java文件中即可完成。


增、删、改、查

前言


以下代码在完成连接数据库的基础之上完成,通过java实现对数据库的增删改查

  
  
  • 1
  • 2
  • 3

一、查询功能
注:
Connection中prepareStatement()方法,提供占位符(?),占位符设置参数setXXX(index,value)。优点:改动参数时,不需改动sql,通过占位符修改。
ResultSet类,作为查询条件的返回集的作用

    //先声明对象,优点在于方便下方任意代码块调用对象信息。
    Connection con=null;
    PreparedStatement pstm=null;
    ResultSet rs=null;

    @Test
    public void testJv3()
    {
    //1,通过JDBC的模板连接上数据库
    con=Jdbc_Conn3.mysqlcon();
    //2,编写sql语句
    String sql="select * from user where uid=?";
    try {
    //3.预编译需要执行的sql
        pstm = con.prepareStatement(sql);
        //prepareStatement中占位符?,通过setXXX(index,values)来进行设置,index从1开始,
        pstm.setInt(1, 1);
        //执行sql并返回查询结果
        ResultSet rs = pstm.executeQuery();
        if(rs.next())
        {
            String password=rs.getString(3);
            String uname=rs.getString(2);
            System.out.println(uname+":"+password);
        }else {
            System.out.println("没有结果");
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        Jdbc_Conn3.mysqlcolse(con, pstm, rs);
    }

    }

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

额外知识点:查询条件输出方式
if():当只有一条结果时,可用if
while():当有多条结果时,可用while


二、增,删,改

增删改,只需要改对应sql即可,以下代码为模板。

PreparedStatement pstm=null;
        Connection con=null;
        //1,实例化MyDataSource
        ComboPooledDataSource mdsc= new ComboPooledDataSource();
        //2.从MyDataSource的池中获得连接对象
        try {
            con= mdsc.getConnection();
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        //3.写sql
        String sql="insert into user values (null,?,?)";
        //4,预编译
        try {
            pstm= con.prepareStatement(sql);
            pstm.setString(1, "zj");
            pstm.setString(2, "zj");
            int col=pstm.executeUpdate();
            if(col>0) {
                System.out.println("添加成功:"+col+"条数");
            }else {
                System.out.println("添加失败");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            JDBCUtils_V3.release(con, pstm, null);
        }
    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

————————————————————上文出自胖胖,转载请附带原文链接

后续更新自学的方法,以及java知识总结
我是哪怕前路坎坷,也不愿负年轻的菜狗,自学之路,共勉

                        <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#csdnc-thumbsup"></use>
                        </svg><span class="name">点赞</span>
                        <span class="count">6</span>
                        </a></li>
                        <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-csdnc-Collection-G"></use>
                        </svg><span class="name">收藏</span></a></li>
                        <li class="tool-item tool-active is-share"><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-csdnc-fenxiang"></use>
                        </svg>分享</a></li>
                        <!--打赏开始-->
                                                <!--打赏结束-->
                                                <li class="tool-item tool-more">
                            <a>
                            <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                            </a>
                            <ul class="more-box">
                                <li class="item"><a class="article-report">文章举报</a></li>
                            </ul>
                        </li>
                                            </ul>
                </div>
                            </div>
            <div class="person-messagebox">
                <div class="left-message"><a href="https://blog.csdn.net/qq_42843730">
                    <img src="https://profile.csdnimg.cn/9/0/6/3_qq_42843730" class="avatar_pic" username="qq_42843730">
                                            <img src="https://g.csdnimg.cn/static/user-reg-year/1x/1.png" class="user-years">
                                    </a></div>
                <div class="middle-message">
                                        <div class="title"><span class="tit"><a href="https://blog.csdn.net/qq_42843730" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">今晚打胖胖</a></span>
                                            </div>
                    <div class="text"><span>发布了13 篇原创文章</span> · <span>获赞 16</span> · <span>访问量 1万+</span></div>
                </div>
                                <div class="right-message">
                                            <a href="https://im.csdn.net/im/main.html?userName=qq_42843730" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信
                        </a>
                                                            <a class="btn btn-sm  bt-button personal-watch" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}">关注</a>
                                    </div>
                            </div>
                    </div>
    
发布了8 篇原创文章 · 获赞 0 · 访问量 265

前言
java连接数据库完整流程为:
1,获得驱动(driver),数据库连接(url),用户名(username),密码(password)基本信息的三种方式。
2,通过获得的信息完成JDBC实现连接数据库。
注:连接前请导入jar包,例:连接mysql数据库需要导入mysql-connector-java-5.1.39-bin.jar包

猜你喜欢

转载自blog.csdn.net/qq_35201262/article/details/103923898