下面列出了java.sql.SQLException#printStackTrace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public User add(User user) {
try (Connection connection = this.source.getConnection();
final PreparedStatement statement = connection
.prepareStatement("insert into users (login) values (?)",
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, user.getLogin());
statement.executeUpdate();
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getInt(1));
return user;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
throw new IllegalStateException("Could not create new user");
}
public String getcontent(String cid) {
conn = this.getConnection();
String content = "";
try {
pstmt = conn
.prepareStatement("select * from news_content where cid='"
+ cid + "'");
rs = pstmt.executeQuery();
while (rs.next()) {
content = rs.getString("ccontent");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeAll(rs, pstmt, conn);
}
return content;
}
/**
* @param matchID - The matchID of the requested game
* @return The Game with the given matchID
*/
public Game getGame(int matchID) {
try {
ResultSet resultSet = statement.executeQuery("select * from sofiav_mathgame.matches where ID=" + matchID);
resultSet.next();
System.out.println("SCORING from db: " + resultSet.getString("Scoring"));
ArrayList<String> playerNames = new ArrayList<String>();
int numPlayers = resultSet.getInt("NumPlayers");
for(int i=1; i<=numPlayers; i++)
playerNames.add(resultSet.getString("Player"+i));
return new Game(matchID, numPlayers, playerNames,
resultSet.getString("Type"), resultSet.getString("Scoring"),
resultSet.getString("Difficulty"), resultSet.getInt("Rounds"));
} catch(SQLException e) {
e.printStackTrace();
}
return new Game(); // Return a blank Game if none could be found
}
protected void createEntries(Connection conn,
Map<String, String> toCreate) {
try {
String query = "INSERT INTO " + TABLE_NAME + "(" + FIELD_VALUE
+ ", " + FIELD_KEY + ", " + FIELD_CONTROLLER
+ ") VALUES(?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(query);
for (String key : toCreate.keySet()) {
String value = toCreate.get(key);
stmt.setString(1, value);
stmt.setString(2, key);
stmt.setString(3, controllerId);
stmt.executeUpdate();
System.out.println("Create Configuration " + key
+ " with value '" + value + "'");
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(ERR_DB_CREATE_SETTINGS);
}
}
public boolean containsKey(Object key)
{
while(true)
{
try
{
return tryContainsKey(key);
}
catch(SQLException e)
{
e.printStackTrace();
try{Thread.sleep(1000);}catch(Exception e2){}
}
}
}
/**
* @Title: setStudentPhoto
* @Description: �����û�ͷ��
* @param: studentInfo
* @return: boolean
*/
public boolean setStudentPhoto(StudentInfo studentInfo) {
Connection connection = DbUtil.getConnection();
String sql = "update user_student set photo = ? where id = ?";
try (PreparedStatement prepareStatement = connection.prepareStatement(sql)) {
prepareStatement.setBinaryStream(1, studentInfo.getPhoto());
prepareStatement.setInt(2, studentInfo.getId());
return prepareStatement.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return update(sql);
}
public static void setOffset(DatabaseHelper helper, String pump, HistoryType historyType, long offset) {
try {
List<Offset> result = helper.getOffsetDao().queryBuilder()
.where().eq("historyType", historyType)
.and().eq("pump", pump).query();
if (result.size() > 0) {
Offset updateOffset = result.get(0);
updateOffset.setOffset(offset);
helper.getOffsetDao().update(updateOffset);
} else {
Offset createOffset = new Offset();
createOffset.setOffset(offset);
createOffset.setPump(pump);
createOffset.setHistoryType(historyType);
helper.getOffsetDao().create(createOffset);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Bean(name = "mysqlDataSource")
@Primary
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(databaseConfig.getUrl());
datasource.setDriverClassName(databaseConfig.getDriverClassName());
datasource.setUsername(databaseConfig.getUsername());
datasource.setPassword(databaseConfig.getPassword());
datasource.setInitialSize(databaseConfig.getInitialSize());
datasource.setMinIdle(databaseConfig.getMinIdle());
datasource.setMaxWait(databaseConfig.getMaxWait());
datasource.setMaxActive(databaseConfig.getMaxActive());
datasource.setMinEvictableIdleTimeMillis(databaseConfig.getMinEvictableIdleTimeMillis());
try {
datasource.setFilters("stat,wall,log4j2");
} catch (SQLException e) {
e.printStackTrace();
}
return datasource;
}
@Override
public void map(Object key, ResultSet rs, Context context)
throws IOException, InterruptedException {
String origAirport;
String destAirport;
String combo;
try {
origAirport = rs.getString("ORIG_AIRPORT");
destAirport = rs.getString("DEST_AIRPORT");
combo = origAirport.compareTo(
destAirport) < 0 ? origAirport + destAirport : destAirport + origAirport;
reusableText.set(combo);
context.write(reusableText, countOne);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Dao<CannulaFilled, Integer> getCannulaFilledDao() {
try {
if (cannulaFilledDao == null) cannulaFilledDao = getDao(CannulaFilled.class);
} catch (SQLException e) {
e.printStackTrace();
}
return cannulaFilledDao;
}
/**
* Deletes courses in DB that doesn't exist on API
*
* @param
*/
public void deleteExpiredCours(ListeDeCours listeDeCours) {
DatabaseHelper dbHelper = new DatabaseHelper(context);
HashMap<String, Cours> coursHashMap = new HashMap<String, Cours>();
for (Cours cours : listeDeCours.liste) {
cours.id = cours.sigle + cours.session;
coursHashMap.put(cours.id, cours);
}
ArrayList<Cours> dbCours = new ArrayList<Cours>();
try {
dbCours = (ArrayList<Cours>) dbHelper.getDao(Cours.class).queryForAll();
ArrayList<ListeDesElementsEvaluation> dbliste = (ArrayList<ListeDesElementsEvaluation>) dbHelper.getDao(ListeDesElementsEvaluation.class).queryForAll();
for (Cours coursNew : dbCours) {
if (!coursHashMap.containsKey(coursNew.id)) {
Dao<Cours, String> coursDao = dbHelper.getDao(Cours.class);
coursDao.deleteById(coursNew.id);
deleteExpiredListeDesElementsEvaluation(coursNew.id);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void saveProfile(ImmutableProfile profile) {
try (Connection c = this.sql.getConnection()) {
try (PreparedStatement ps = c.prepareStatement(replaceTableName(INSERT))) {
ps.setString(1, UndashedUuids.toString(profile.getUniqueId()));
ps.setString(2, profile.getName().get());
ps.setTimestamp(3, new Timestamp(profile.getTimestamp()));
ps.setString(4, profile.getName().get());
ps.setTimestamp(5, new Timestamp(profile.getTimestamp()));
ps.execute();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean schemaExists(String name){
ResultSet rs = this.query("SELECT * FROM information_schema.schemata WHERE schema_name = '" + name.toLowerCase() + "'");
try {
if(rs.next()){
return true;
}else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public static void updateRole(Client client){
try(Connection conn = connect();
PreparedStatement pstm = conn.prepareStatement(clientRoleUpdate)){
pstm.setInt(1, client.getRole().getPrestige());
pstm.setString(2, client.getName());
pstm.setString(3, client.getGroupId());
pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void connect(){
Connection connection = getConnection();
System.out.append("Connected!\n");
try {
System.out.append("Autocommit: " + connection.getAutoCommit() + '\n');
System.out.append("DB name: " + connection.getMetaData().getDatabaseProductName() + '\n');
System.out.append("DB version: " + connection.getMetaData().getDatabaseProductVersion() + '\n');
System.out.append("Driver: " + connection.getMetaData().getDriverName() + '\n');
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public Map<String, String> getAliases() {
Map<String, String> stringMap = new HashMap<String, String>();
try {
PreparedStatement statement = this.mDb.getPreparedStatement("select * from aliases", null);
ResultSet c = statement.executeQuery();
while (c.next()) {
int idColumn = c.findColumn(AbstractDb.AliasColumns.ADDRESS);
String address = null;
String alias = null;
if (idColumn > -1) {
address = c.getString(idColumn);
}
idColumn = c.findColumn(AbstractDb.AliasColumns.ALIAS);
if (idColumn > -1) {
alias = c.getString(idColumn);
}
stringMap.put(address, alias);
}
c.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return stringMap;
}
public static void recordData(Connection conn, TrafficUnit tu, double speed) {
String sql = "insert into data(vehicle_type, horse_power, weight_pounds, passengers_count, payload_pounds, speed_limit_mph, " +
"temperature, road_condition, tire_condition, traction, speed) values(?,?,?,?,?,?,?,?,?,?,?)";
/*
System.out.println(" " + sql + ", params=" + tu.getVehicleType() + ", " + tu.getHorsePower() + ", " + tu.getWeightPounds()
+ ", " + tu.getPassengersCount() + ", " + tu.getPayloadPounds() + ", " + tu.getSpeedLimitMph() + ", " + tu.getTemperature()
+ ", " + tu.getRoadCondition() + ", " + tu.getTireCondition()+ ", " + tu.getTraction() + ", " + speed);
*/
try {
int i = 1;
PreparedStatement st = conn.prepareStatement(sql);
st.setString(i++, tu.getVehicleType().name());
st.setInt(i++, tu.getHorsePower());
st.setInt(i++, tu.getWeightPounds());
st.setInt(i++, tu.getPassengersCount());
st.setInt(i++, tu.getPayloadPounds());
st.setDouble(i++, tu.getSpeedLimitMph());
st.setInt(i++, tu.getTemperature());
st.setString(i++, tu.getRoadCondition().name());
st.setString(i++, tu.getTireCondition().name());
st.setDouble(i++, tu.getTraction());
st.setDouble(i++, speed);
int count = st.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
/**
* 根据模块返回搜索结果, 具有分组性质.
*
* @param module
* @return
*/
public List<AlbumInfo> queryAllCategory(Module module)
{
List<AlbumInfo> albumInfoList = null;
try
{
QueryBuilder<AlbumInfo, Long> queryBuilder = mAlbumDao.queryBuilder();
queryBuilder.groupBy("category");
queryBuilder.orderBy("orderby", true);
albumInfoList = queryBuilder.where().eq("module", module.value).query();
}
catch (SQLException e)
{
e.printStackTrace();
}
if (encrypt_mode)
{
if (albumInfoList == null || albumInfoList.isEmpty())
{
return null;
}
int size = albumInfoList.size();
for (int i = 0; i < size; i++)
{
albumInfoList.get(i).setCoverurl(SecurityTu123.decodeImageUrl(albumInfoList.get(i).getCoverurl()));
}
}
return albumInfoList;
}
public void saveStats(final PlayerStat pData) {
boolean sqlEnabled = SkyWarsReloaded.get().getConfig().getBoolean("sqldatabase.enabled");
if (!sqlEnabled) {
try {
File dataDirectory = SkyWarsReloaded.get().getDataFolder();
File playerDataDirectory = new File(dataDirectory, "player_data");
if (!playerDataDirectory.exists() && !playerDataDirectory.mkdirs()) {
return;
}
File playerFile = new File(playerDataDirectory, pData.getId() + ".yml");
if (!playerFile.exists()) {
SkyWarsReloaded.get().getLogger().info("File doesn't exist!");
return;
}
copyDefaults(playerFile);
FileConfiguration fc = YamlConfiguration.loadConfiguration(playerFile);
fc.set("uuid", pData.getId());
fc.set("wins", pData.getWins());
fc.set("losses", pData.getLosses());
fc.set("kills", pData.getKills());
fc.set("deaths", pData.getDeaths());
fc.set("elo", pData.getElo());
fc.set("xp", pData.getXp());
fc.set("pareffect", pData.getParticleEffect());
fc.set("proeffect", pData.getProjectileEffect());
fc.set("glasscolor", pData.getGlassColor());
fc.set("killsound", pData.getKillSound());
fc.set("winsound", pData.getWinSound());
fc.set("taunt", pData.getTaunt());
fc.save(playerFile);
} catch (IOException ioException) {
System.out.println("Failed to load faction " + pData.getId() + ": " + ioException.getMessage());
}
} else {
Database database = SkyWarsReloaded.getDb();
if (database.checkConnection()) {
return;
}
Connection connection = database.getConnection();
PreparedStatement preparedStatement = null;
try {
String query = "UPDATE `sw_player` SET `player_name` = ?, `wins` = ?, `losses` = ?, `kills` = ?, `deaths` = ?, `elo` = ?, `xp` = ?, `pareffect` = ?, " +
"`proeffect` = ?, `glasscolor` = ?,`killsound` = ?, `winsound` = ?, `taunt` = ? WHERE `uuid` = ?;";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, pData.getPlayerName());
preparedStatement.setInt(2, pData.getWins());
preparedStatement.setInt(3, pData.getLosses());
preparedStatement.setInt(4, pData.getKills());
preparedStatement.setInt(5, pData.getDeaths());
preparedStatement.setInt(6, pData.getElo());
preparedStatement.setInt(7, pData.getXp());
preparedStatement.setString(8, pData.getParticleEffect());
preparedStatement.setString(9, pData.getProjectileEffect());
preparedStatement.setString(10, pData.getGlassColor());
preparedStatement.setString(11, pData.getKillSound());
preparedStatement.setString(12, pData.getWinSound());
preparedStatement.setString(13, pData.getTaunt());
preparedStatement.setString(14, pData.getId());
preparedStatement.executeUpdate();
} catch (final SQLException sqlException) {
sqlException.printStackTrace();
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (final SQLException ignored) {
}
}
}
}
}
public ArrayList<Order> getUnfinishedOrder(int shopId, int page) {
ArrayList<Order> orders = new ArrayList<Order>();
try {
String sql = "select * from goods_order where shop_id = ? "
+ "and order_status='待发货' "
+ "group by order_time DESC "
+ "limit ?,10;";
connection = DBUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, shopId);
preparedStatement.setInt(2, (page - 1) * 10);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Order od = new Order();
od.setOrderId(resultSet.getLong("order_id"));
od.setShopId(resultSet.getInt("shop_id"));
od.setUserId(resultSet.getInt("user_id"));
od.setOrderTime(resultSet.getTimestamp("order_time"));
od.setAnnotation(resultSet.getString("annotation"));
od.setTotal(resultSet.getInt("total"));
// int receiverId = resultSet.getInt("receiver_id");
// Receiver receiver = new Receiver();
// String sql1 = "select * from receiver where receiver_id =
// ?;";
// PreparedStatement ps = connection.prepareStatement(sql1);
// ps.setInt(1, receiverId);
// ResultSet rs = ps.executeQuery();
// if (rs.next()) {
// receiver.setUserId(rs.getInt("user_id"));
// receiver.setReceiverId(rs.getInt("receiver_id"));
// receiver.setAddress(rs.getString("address"));
// receiver.setName(rs.getString("name"));
// receiver.setPhone(rs.getString("phone"));
// }
// od.setReceiver(receiver);// 获得收货人
// od.setGoodsInOrder(getGoodsInOrder(resultSet.getLong("order_id")));
orders.add(od);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return orders;
}