JDBC添加数据

package com.atguigu.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class ConnectionTest {

    
    public static void main(String[] args) {
        
        Connection conn = null;
        Statement stmt = null;
        String sql = null;
        Scanner sr = new Scanner(System.in);
        System.out.println("请输入等级:");
        String level = sr.next();
        System.out.println("请输入最低工资:");
        int min_sal = sr.nextInt();
        System.out.println("请输入最高工资:");
        int max_sal = sr.nextInt();
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.创建连接对象
             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myemployees","root", "123456890");
            //3.创建statement对象
             stmt = conn.createStatement();
            //4.执行SQL语句
             sql = "INSERT INTO `myemployees`.`job_grades`(`grade_level`,`lowest_sal`,`highest_sal`)VALUES ('"+level+"','"+min_sal+"','"+max_sal+"')";
            int row = stmt.executeUpdate(sql);
            if(row>0) {
                System.out.println("执行成功");
            }else {
                System.out.println("执行失败");
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if(stmt!=null) {
                stmt.close();
                }
                if(conn!=null&&conn.isClosed()==false) {
                    conn.close();
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        
    }
    
    
}

 

posted @ 2020-08-29 13:11  vkd  阅读(225)  评论(0)    收藏  举报