Java 在Idea平臺用JDBC連線MySQL資料庫並插入值
阿新 • • 發佈:2019-02-05
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(); }