前置:
mysql-connector-java-x.x.xx-bin.jar (e.g. mysql-connector-java-5.1.26-bin.jar)
Get connection:
public static Connection getConnection() {
Connection conn = null;
String url = "jdbc:mysql://192.168.22.250:3306/dbname?"
+ "user=test&password=111&useUnicode=true&characterEncoding=UTF8";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
Update:
public static void update(Connection conn, ResultSet rs, String updateField, Integer updateValue) {
String sql = "update transform set " + updateField + " = ? where idcard = ? and mobile = ?";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1,updateValue);
ps.setString(2,rs.getString(1));
ps.setString(3,rs.getString(2));
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
Select:
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
// table:transform
String sql2 = "select * from transform";
ResultSet rs2 = stmt.executeQuery(sql2);
while (rs2.next()) {
// key
// System.out.println("transform:" + rs2.getString(1) + "\t" + rs2.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
}
}