期中考试前准备--数据库插入代码

import java.sql.*;
import java.util.Scanner;
public class jdbcinsert {
    public static void main(String[]args) {
        final String URL = "jdbc:mysql://localhost:3306/test";
        final String USERNAME = "root";
        final String PWD = "12345";
        Connection connection = null;
        PreparedStatement  pstmt = null;
        Scanner con=new Scanner(System.in);
        String classname;
        String teacher;
        String didian;

        classname=con.nextLine();
        teacher=con.nextLine();
        didian=con.nextLine();
        try {
            // a.导入驱动,加载具体的驱动类
            Class.forName("com.mysql.jdbc.Driver");// 加载具体的驱动类
            // b.与数据库建立连接
            connection = DriverManager.getConnection(URL, USERNAME, PWD);
            

            //PreparedStatement
            String sql = "insert into student values(?,?,?,?)";
            pstmt = connection.prepareStatement(sql);//预编译
            pstmt.setInt(1, 20194158);
            pstmt.setString(2, classname);
            pstmt.setString(3, teacher);
            pstmt.setString(4, didian);
            
            int count =pstmt.executeUpdate() ;
            
            // d.处理结果
            if (count > 0) {  
                System.out.println("操作成功!");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                 if(pstmt!=null) pstmt.close();// 对象.方法
                 if(connection!=null)connection.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
原文地址:https://www.cnblogs.com/jz-no-bug/p/14229706.html