JAVA连接数据库的方法

一、连接数据库

连接数据库需要两步,加载驱动和连接数据库。不同数据库的数据库地址和驱动名不同。笔者主要使用mysql,所以mysql写的相对详细一点,其他的都是网上找的。

1、Mysql

    //数据库地址
    String url = "jdbc:mysql://localhost:3306/webtest";//webtest为数据库名
    //数据库的用户名和密码
    String user = "root";
    String userpassword = "123456";
    try{
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //连接数据库,获取连接对象
            conn = DriverManager.getConnection(url,user,userpassword); 
        }catch(ClassNotFoundException e){
            out.println("找不到驱动类");
        }catch(SQLException e){
            out.println("连接数据库失败");
        }

2、Oracle

    Class.forName("oracle.jdbc.driver.OracleDriver");  
    String url="jdbc:oracle:thin:@localhost:1521:orcl";//orcl为sid
    Connection conn= DriverManager.getConnection(url,user,password); 

3、Db2

   Class.forName("com.ibm.db2.jdbc.app.DB2Driver ");
   String url="jdbc:db2://localhost:5000/sample"; //sample为你的数据库名
   Connection conn= DriverManager.getConnection(url,user,password);

4、SQL Server

    //连接mssql 2000 
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver ").newInstance(); 
    String URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=db";  
    Connection conn= DriverManager.getConnection(url,user,password); 
    //连接mssql 2005 + 
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); 
    String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=db";  
    Connection conn= DriverManager.getConnection(url,user,password); 
    //通用方式: 
    Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance(); 
    String url="jdbc:jtds:sqlserver://localhost:1433;DatabaseName=db"; 
    Connection conn= DriverManager.getConnection(url,user,password);

二、修改数据

修改数据包括对数据库的增删改,其步骤是一致的,不同的只是数据库语句。

    Statement stmt = null;
    try{//创建语句对象Statement
        stmt = conn.createStatement();
        //定义添加语句
        String addUser = "INSERT INTO user(userid,username,password) VALUES(null,'zhou','123456')";
        //定义更新语句
        String updateUser = "UPDATE user SET password='123' WHERE userid=2";
        //定义删除语句
        String deleteUser = "DELETE FROM user WHERE userid=3";
        //执行语句
        //添加
        stmt.executeUpdate(addUser);
        //更新
        stmt.executeUpdate(updateUser);
        //删除
        stmt.executeUpdate(deleteUser);
    }catch(SQLException e){
        out.println("修改失败");
    }

三、查询

根据定义的查询语句,可以实现对任意数据的查询

    ResultSet rs = null;
    //查询
    try{
        //创建语句对象Statement
        stmt = conn.createStatement();
        //定义查询语句
        String queryAll = "SELECT * FROM user";
        //String query1 = "SELECT userid username FROM user";//只查询userid和username
        //执行查询语句,获得结果集
        rs = stmt.executeQuery(queryAll);
        //遍历结果集,获取所有记录
        while(rs.next()){
            //获取第一个字段userid的值
            int userid = rs.getInt(1);
            //获取第二个字段username的值
            String username = rs.getString(2);
            //获取第三个字段password的值
            String password = rs.getString(3);
            out.println("用户id:"+userid);
            out.println("用户名:"+username);
            out.println("密码:"+password);
            out.println("<br/>");
        }
    }catch(SQLException e){
        out.println("查询失败");
    }

四、关闭数据库

按照从里到外的顺序,先关闭结果集对象,再关闭语句对象,最后关闭连接对象

    //关闭数据库
    try{
        if(rs!=null){
            rs.close();
            rs = null;
        }
        if(stmt!=null){
            stmt.close();
            stmt = null;
        }
        if(conn!=null){
            conn.close();
            conn = null;
        }
    }catch(Exception e){
        out.println("数据库关闭异常");
    }

五、预处理语句对象-PreparedStatement

这个继承了Statement接口,所以,它拥有Statement的所有功能,并更加灵活。主要体现在PreparedStatement对象的SQL语句可以接收多个参数,并用“?”来代替。在实际开发中,这个对象更加常用。

    PreparedStatement ps = null;
    try{
        //定义带参数的sql语句
        String sql = "INSERT INTO user(userid,username,password) VALUES(null,?,?)";
        ps = conn.prepareStatement(sql);
        //设置参数值
        ps.setString(1,username);
        ps.setString(2,password);
        ps.executeUpdate();
        System.out.println("添加成功");
    }catch(SQLException e){
        out.println("添加失败");
    }

六、完整例子

1、查询

本例子包含了数据库连接,查询数据,并关闭数据库。其实就是把上面的代码拼接到一块。

    String url = "jdbc:mysql://localhost:3306/webtest";
    String user = "root";
    String userpassword = "123456";
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
        try{
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //连接数据库,获取连接对象
            conn = DriverManager.getConnection(url,user,userpassword); 
        }catch(ClassNotFoundException e){
            out.println("找不到驱动类");
        }catch(SQLException e){
            out.println("连接数据库失败");
        }
    //查询
    try{
        //创建语句对象Statement
        stmt = conn.createStatement();
        //定义查询语句
        String queryAll = "SELECT * FROM user";
        //执行查询语句
        rs = stmt.executeQuery(queryAll);
        //获取所有记录
        while(rs.next()){
            //获取第一个字段userid的值
            int userid = rs.getInt(1);
            //获取第二个字段username的值
            String username = rs.getString(2);
            //获取第三个字段password的值
            String password = rs.getString(3);
            out.println("用户id:"+userid);
            out.println("用户名:"+username);
            out.println("密码:"+password);
            out.println("<br/>");
        }
    }catch(SQLException e){
        out.println("查询失败");
    }

    //关闭数据库
    try{
        if(rs!=null){
            rs.close();
            rs = null;
        }
        if(stmt!=null){
            stmt.close();
            stmt = null;
        }
        if(conn!=null){
            conn.close();
            conn = null;
        }
    }catch(Exception e){
        out.println("数据库关闭异常");
    }

2、添加数据

这个例子使用了PreparedStatement对象

    String url = "jdbc:mysql://localhost:3306/webtest";
    String user = "root";
    String userpassword = "123456";
    Connection conn = null;
    Statement stat = null;
    PreparedStatement ps = null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(url,user,userpassword); 
    }catch(ClassNotFoundException e){
        out.println("找不到驱动类");
    }catch(SQLException e){
        out.println("连接数据库失败");
    }
    try{
        String sql = "INSERT INTO user(userid,username,password) VALUES(null,?,?)";
        ps = conn.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);
        ps.executeUpdate();
        System.out.println("添加成功");
    }catch(SQLException e){
        out.println("添加失败");
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值