Java 在Idea平台用JDBC连接MySQL数据库并插入值

public class file {

    public static final String url = "jdbc:mysql://localhost:3306/carinfo";
    public static final String name = "com.mysql.jdbc.Driver";
    public static final String user = "root";
    public static final String password = "";

    public Connection conn = null;

    public void DBHelper(){

        try {
            Class.forName(name);
            conn = DriverManager.getConnection(url, user, password);
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM msg2 WHERE VINID LIKE '-%'");
            while (rs.next()){

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void close(){
        try {
            this.conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
try {
                        String sql="insert into dvalue(start_mileage,end_mileage) values(?,?)";//会抛出异常
                        PreparedStatement preStmt=conn.prepareStatement(sql);//conn是上一个程序的conn
                        preStmt.setLong(1, km);
                        preStmt.setLong(2, km);

                        preStmt.executeUpdate();
                        System.out.println("插入到数据库成功");
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }


你可能感兴趣的:(java)