浅谈IDEA中JBDC的简单增删查改操作及简单封装

连接数据库

1.加载驱动

Class.forName("com.mysql.jdbc.Driver");

本行代码主要作用是加载(注册)数据库驱动(到JVM)

2.创建链接

Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=true&characterEncoding=utf8","root","123");
System.out.println("创建链接成功");

通过connection与DriverManager建立与数据库的连接

对数据库的操作

查询账户操作

3.创建sql语句

String sql = "select * from user";

4.得到statement对象

statement = connection1.prepareStatement(sql);

5.执行sql语句,得到结果集

resultSet = statement.executeQuery();

6.处理结果集

while(resultSet.next()){
                int Uno = resultSet.getInt("id");

                String Uname = resultSet.getString("username");

                String Upwd = resultSet.getString("password");

                System.out.println("用户编号:\t" + Uno + "   用户名:\t" + Uname + "   用户密码:\t" + Upwd);

            }

7.关闭对象,回收数据库资源

if(resultSet!=null){
                    try {
                        resultSet.close();
                    }catch (SQLException e){
                        e.printStackTrace();
                    }
                }
                if(statement!=null){
                    try {
                        statement.close();
                    }catch (SQLException e){
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    try {
                        connection.close();
                    }catch (SQLException e){
                        e.printStackTrace();
                    }
                }

关闭结果集-->关闭数据库操作对象-->关闭连接

结果

增添账户操作

完整代码

public class insert {
    public static void main(String[] args){

        PreparedStatement statement=null;
        Connection connection=null;
        //1.加载驱动
        try{
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接
            Connection connection1 = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=true&characterEncoding=utf8","root","123");

            System.out.println("创建链接成功");
            Scanner sc2=new Scanner(System.in);
            Scanner sc3=new Scanner(System.in);
            //3.创建sql语句
            String sql="insert into user (id,username,password) values(?,?,?)";
            //4.得到statement对象
            System.out.print("请输入要添加的用户编号:");

            int Uno = sc2.nextInt();

            System.out.print("请输入要添加的用户名:");

            String Uname = sc3.nextLine();

            System.out.print("请输入要添加的用户密码:");

            String Upwd = sc3.nextLine();
            statement=connection1.prepareStatement(sql);
            statement.setInt(1,Uno);
            statement.setString(2,Uname);
            statement.setString(3,Upwd);

            statement.executeUpdate();




        }catch(Exception e){
            e.printStackTrace();
        }finally{

            if(statement!=null){
                try {
                    statement.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                try {
                    connection.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }
}

结果

修改用户操作

核心代码

            Scanner upd1=new Scanner(System.in);
            Scanner upd2=new Scanner(System.in);
            //3.创建sql语句
                       String updSql="update user set username=? , password=? where id=?";
            //4.得到statement对象
            statement2=connection2.prepareStatement(updSql);
            System.out.print("请输入要修改的用户编号:");
            int aid = upd1.nextInt();
            System.out.print("请输入修改后的用户名:");
            String un = upd2.nextLine();
            System.out.print("请输入修改后的用户密码:");
            String pw = upd2.nextLine();

            statement2.setString(1,un);
            statement2.setString(2,pw);
            statement2.setInt(3,aid);


            statement2.executeUpdate();

结果

删除用户操作

核心代码

Scanner del=new Scanner(System.in);

            //3.创建sql语句
            String delSql="delete from user where (id)=(?)";
            //4.得到statement对象
            System.out.print("请输入要删除的用户编号:");

            int id = del.nextInt();
            statement1=connection.prepareStatement(delSql);

            statement1.setInt(1,id);

            statement1.executeUpdate();

结果

连接数据库与回收数据库资源的封装

在src下新建util包,新建一个DBUtil类用来封装各种操作同样需求的操作。

public class DBUtil {
        public static Connection getConnection(){
            try {
                Class.forName("com.mysql.jdbc.Driver");
                //2.创建连接
                Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=true&characterEncoding=utf8","root","123");

                return conn;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;

        }

        public static void close(ResultSet resultSet, Statement statement,Connection connection){
                if(resultSet!=null){
                    try {
                        resultSet.close();
                    }catch (SQLException e){
                        e.printStackTrace();
                    }
                }
                if(statement!=null){
                    try {
                        statement.close();
                    }catch (SQLException e){
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    try {
                        connection.close();
                    }catch (SQLException e){
                        e.printStackTrace();
                    }
                }

        }
}

封装后便可将原有的代码修改,形式变得更加简洁:

public class JDBC {

    public static void main(String[] args){
        ResultSet resultSet=null;
        PreparedStatement statement=null;
        Connection connection=null;
        //1.加载驱动
        try{
        Connection connection1= DBUtil.getConnection();
        System.out.println("创建链接成功");
        //3.创建sql语句
        String sql = "select * from user";

        //4.得到statement对象
        statement = connection1.prepareStatement(sql);
        //5.执行sql 得到结果集
         resultSet = statement.executeQuery();
         //6.处理结果集
            while(resultSet.next()){
                int Uno = resultSet.getInt("id");

                String Uname = resultSet.getString("username");

                String Upwd = resultSet.getString("password");

                System.out.println("用户编号:\t" + Uno + "   用户名:\t" + Uname + "   用户密码:\t" + Upwd);
                //System.out.println(resultSet.getInt("id" ));
                //System.out.println(resultSet.getString( "username"));
                //System.out.println(resultSet.getString( "password"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            DBUtil.close(resultSet,statement,connection);
        }

    }


}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
首先,在IDEA需要引入SqlServer的JDBC驱动,可以在pom.xml文件添加如下依赖: ```xml <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>8.4.1.jre11</version> </dependency> ``` 然后,可以使用Java的JDBC API对SqlServer进行增删查改操作。下面是一个简单的示例代码: ```java import java.sql.*; public class SqlServerDemo { public static void main(String[] args) { Connection conn = null; try { // 连接SqlServer数据库 conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=test", "username", "password"); // 插入数据 String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 1); pstmt.setString(2, "Tom"); pstmt.setInt(3, 18); pstmt.executeUpdate(); // 查询数据 sql = "SELECT * FROM student WHERE id = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age")); } // 更新数据 sql = "UPDATE student SET age = ? WHERE id = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 20); pstmt.setInt(2, 1); pstmt.executeUpdate(); // 删除数据 sql = "DELETE FROM student WHERE id = ?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 1); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } ``` 其,`jdbc:sqlserver://localhost:1433;DatabaseName=test`表示连接本地SqlServer数据库的test数据库,需要将username和password替换为实际的用户名和密码。代码演示了如何插入、查询、更新和删除数据。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值