1.JDBC

Posted 重庆刘亦菲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.JDBC相关的知识,希望对你有一定的参考价值。

用DriverManager.register(new Driver())

public class JDBC {

    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub

        //1.获取链接
          //a.注册驱动
        DriverManager.registerDriver(new Driver());
        
        String url="jdbc:mysql://localhost:3306/day07";
        String user="root";
        String password="moujinling321";
          //获取链接
        Connection conn=DriverManager.getConnection(url, user, password);
        
        //2.编写sql
        String sql="select * from user";
        
        //3.获取sql语句执行对象
        Statement st=conn.createStatement();
        
        //4.执行sql
        ResultSet rs=st.executeQuery(sql);
        
        //5.处理结果
        while(rs.next()){
            int id=rs.getInt("id");
            String username=rs.getString("username");
            String pwd=rs.getString("password");
            String email=rs.getString("email");
            
            System.out.println(id+"::"+username+"::"+pwd+"::"+email);
        }
        
        //6.释放资源(先打开后关闭)
        rs.close();
        st.close();
        conn.close();

    }
}

 

用Class.forName("com.mysql.jdbc.Driver")注册来实现CRUD

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

public class CRUDDemo {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        
        //插入
        insert();
        
        //更新
        updateByUsername("lily","尼古拉斯。丽丽");
        
        //查询
        getByUsername("尼古拉斯。张三");
        
        //删除
        deleteByUsername("尼古拉斯。丽丽");

    }

    private static void deleteByUsername(String str) throws ClassNotFoundException, SQLException {
        
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day07", "root","moujinling321");
        
        String sql="delete from user where username=‘"+str+"‘";
        Statement st=conn.createStatement();
        int len=st.executeUpdate(sql);
        if(len>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
        
        st.close();
        conn.close();
    }

    private static void getByUsername(String str) throws ClassNotFoundException, SQLException {
        
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day07","root","moujinling321");
        
        //limit int1 int2
        //** limit 1 从索引为0开始向后取一条记录,等价于 limit 0 1
        //** limit 0 10 从索引为0开始向后取10条记录
        String sql="select * from user where username=‘"+str+"‘ limit 1";
        
        Statement st=conn.createStatement();
        
        ResultSet rs=st.executeQuery(sql);
        
        while(rs.next()){
            Object id=rs.getObject(1);
            String username=rs.getString("username");
            String password=rs.getString("password");
            String email=rs.getString("email");
            
            System.out.println(id+"::"+username+"::"+password+"::"+email);
        }
        rs.close();
        st.close();
        conn.close();
        
    }

    private static void updateByUsername(String str1, String str2) throws ClassNotFoundException, SQLException {
        //获取连接
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day07","root","moujinling321");
        //编写sql
        String sql="update user set username=‘"+str2+"‘ where username =‘"+str1+"‘";
        //获取sql执行对象
        Statement st=conn.createStatement();
        //执行sql
        int len=st.executeUpdate(sql);
        //处理结果
        if(len>0){
            System.out.println("插入成功");
        }else{
            System.out.println("插入失败");
        }
        //释放资源
        st.close();
        conn.close();
    }

    private static void insert() throws ClassNotFoundException, SQLException{
        
        //获取连接
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day07","root","moujinling321");
        //编写sql
        String sql="insert into user values(null,‘张三‘,‘123‘,‘[email protected]‘)";
        //获取语句执行者
        Statement st=conn.createStatement();
        //执行sql
        int i=st.executeUpdate(sql);
        //处理结果
        if(i>0){
            System.out.println("成功");
        }else{
            System.out.println("失败");
        }
        //释放资源
        st.close();
        conn.close();
    }
}

 

jdbc.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day07
user=root
password=moujinling321

 

JDBCUtil

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class JDBCUtil {

    static final String DRIVERCLASSNAME;
    static final String URL;
    static final String USER;
    static final String PASSWORD;
    
    static{
        /**
         * ResourceBundle:用于加载properties文件
         *      ResourceBundle bundle=ResourceBundle.getBundle(文件名称);
         *   通过bundle的getString(key)就可以获取指定value
         *    String url=bundle.getString("url");
         */
        ResourceBundle bundle=ResourceBundle.getBundle("jdbc"); //不需要后缀名
        DRIVERCLASSNAME=bundle.getString("driverClassName");
        URL=bundle.getString("url");
        USER=bundle.getString("user");
        PASSWORD=bundle.getString("password");
    }
    
    static{
        try {
            Class.forName(DRIVERCLASSNAME);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
  //获取连接
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(URL,USER,PASSWORD);
    }
    
    public static void closeResources(Connection conn,Statement st){
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    public static void closeResources(Connection conn,Statement st,ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

 

测试JDBCUtil

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import util.JDBCUtil;

public class TestUtils {    
    public static void main(String[] args) throws SQLException {
        // TODO Auto-generated method stub

        insert(6,"李四","abcd","[email protected]");
        
        delete("李四");
        
        update(6,5);
        
        query(2);
    }
    

    public static void query(int i) throws SQLException {
        String sql="select * from user where id="+i;
        Connection conn=JDBCUtil.getConnection();
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery(sql);
        while(rs.next()){
            Object id=rs.getObject(1);
            String username=rs.getString(2);
            String password=rs.getString("password");
            String email=rs.getString("email");
            
            System.out.println(id+":"+username+":"+password+":"+email);
        }
        JDBCUtil.closeResources(conn, st, rs);
    }

    public static void update(int i, int j) throws SQLException {
        String sql="update user set id="+j+" where id="+i;
        Connection conn=JDBCUtil.getConnection();
        Statement st=conn.createStatement();
        ResultSet rs=null;
        int len=st.executeUpdate(sql);
        if(len>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }
        JDBCUtil.closeResources(conn, st, rs);
    }

    public static void delete(String name) throws SQLException {
        String sql="delete from user where username=‘"+name+"‘";
        Connection conn=JDBCUtil.getConnection();
        Statement st=conn.createStatement();
        ResultSet rs=null;
        int len=st.executeUpdate(sql);
        if(len>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
        JDBCUtil.closeResources(conn, st, rs);
    }

    public static void insert(int id,String name,String pwd,String email) throws SQLException{
        String sql="insert into user values("+id+",‘"+name+"‘,‘"+pwd+"‘,‘"+email+"‘)";
        Connection conn=JDBCUtil.getConnection();
        Statement st=conn.createStatement();
        ResultSet rs=null;
        int len=st.executeUpdate(sql);
        if(len>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }
        JDBCUtil.closeResources(conn, st, rs);
    }
}

 

含预编译的CURD

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import login.User;
import util.JDBCUtil;

public class PPCRUDDemo {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        //insert
        insert("佳佳","jiajia","[email protected]");
        
        //update
        updateByName("张嘉佳","佳佳");
        
        //select
        getByName("张嘉佳");
        
        //delete
        deleteByName("张嘉佳");
    }

    private static void deleteByName(String string) {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        
        try {
            conn=JDBCUtil.getConnection();
            String sql="delete from user where username=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1, string);
            int len=ps.executeUpdate();
            if(len>0){
                System.out.println("success");
            }else{
                System.out.println("fail");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.closeResources(conn, ps, rs);
        }
        
    }

    private static void getByName(String name)  {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        
        try {
            conn=JDBCUtil.getConnection();
            String sql="select * from user where username=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            rs=ps.executeQuery();
            while(rs.next()){
                System.out.println(rs.getInt(1)+":"+rs.getString(2)+":"+rs.getString(3)+":"+rs.getString(4));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.closeResources(conn,ps,rs);
        }
        
    }

    private static void updateByName(String str1, String str2) {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        
        try {
            conn=JDBCUtil.getConnection();
            String sql="update user set username=? where username=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1, str2);
            ps.setString(2, str1);
            int len=ps.executeUpdate();
            if(len>0){
                System.out.println("success");
            }else{
                System.out.println("fail");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.closeResources(conn, ps, rs);
        }
        
    }

    private static void insert(String name, String pwd, String email) throws ClassNotFoundException, SQLException {
        //获取连接
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day07","root","moujinling321");
        
        //编写sql
        String sql="insert into user values(null,?,?,?)";
        
        //创建预编译执行语句
        PreparedStatement ps=conn.prepareStatement(sql);
        
        //设置参数
        ps.setString(1,name);
        ps.setString(2, pwd);
        ps.setString(3, email);
        
        //执行sql
        int len=ps.executeUpdate();
        
        //处理结果
        if(len>0){
            System.out.println("success");
        }else{
            System.out.println("fail");
        }
        
        //释放资源
        ps.close();
        conn.close();
    }
}

 

登录案例:

public class User {

    private Integer id;
    private String username;
    private String password;
    private String email;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public User() {
        super();
    }
    public User(Integer id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
    }
    
}
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import util.JDBCUtil;
/**
 * 用户操作类     专门操作数据库
 * @author mjl
 *
 */
public class UserOperation {

    public User login(String username, String password) {
        // 通过jdbc查询用户是否存在
        Connection conn=null;
        Statement st=null;
        ResultSet rs=null;
        
        try {
            conn=JDBCUtil.getConnection();
            String sql="select * from user where username=‘"+username+"‘ and password=‘"+password+"‘";
            st=conn.createStatement();
            rs=st.executeQuery(sql);
            if(rs.next()){
                return new User(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.closeResources(conn, st, rs);
        }
        
        return null;
    }

}
import java.util.Scanner;

public class LoginDemo {

    public static void main(String[] args) {
        
        //1.获取用户名和密码
        Scanner sc=new Scanner(System.in);
        
        System.out.println("请输入用户名:");
        String username=sc.nextLine();
        
        System.out.println("请输入密码:");
        String password=sc.nextLine();        
        
        //2.调用operation的login方法
        UserOperation uo=new UserOperation();
        User user=uo.login(username,password);
        
        //3.处理结果
        if(user==null){
            System.out.println("查无此人");
        }else{
            System.out.println("登录成功");
        }
    }
}

 




以上是关于1.JDBC的主要内容,如果未能解决你的问题,请参考以下文章

Mysql JDBC代码实例

微信小程序代码片段

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板