美文网首页
黑猴子的家:JDBC -> PreparedStateme

黑猴子的家:JDBC -> PreparedStateme

作者: 黑猴子的家 | 来源:发表于2019-03-01 10:43 被阅读0次
    1、检查是否继承了AutoCloseable类
    2、改写代码
    package com.yinggu.demo3;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.util.Scanner;
    import org.junit.Test;
    import com.yinggu.utils.JDBCUtils;
    
     * 使用PreparedStatement实现增删改查
     * 
     * @author:黑猴子的家
     * @博客 :https://www.jianshu.com/u/37fd8e2dff4c
    
    public class TestPreparedStatement {
        Scanner input = new Scanner(System.in);
        @Test
        public void testInsert() {
            System.out.println("请输入考生的详细信息");
            System.out.print("Type:");
            int type = input.nextInt();
            System.out.print("IDCard:");
            String idCard = input.next();
            System.out.print("ExamCard:");
            String examCard = input.next();
            System.out.print("StudentName:");
            String studentName = input.next();
            System.out.print("location:");
            String location = input.next();
            System.out.print("Grade:");
            int grade = input.nextInt();
            // ------------------------以下为连接数据库的步骤-------------------
            try (
                // 1.获取连接
                Connection connection = JDBCUtils.getConnection();
                // 2.访问数据库,执行操作
                PreparedStatement statement = connection.prepareStatement(
                    "insert into examstudent values(null,?,?,?,?,?,?)");
            ) 
            {
                statement.setInt(1, type);
                statement.setString(2, idCard);
                statement.setString(3, examCard);
                statement.setString(4, studentName);
                statement.setString(5, location);
                statement.setInt(6, grade);
                int update = statement.executeUpdate();
                System.out.println(update > 0 ? "success" : "failure");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:黑猴子的家:JDBC -> PreparedStateme

          本文链接:https://www.haomeiwen.com/subject/swwruqtx.html