我有以下程序可将表情符号和任何文本插入我的 MySql AWS 数据库。我无法在我的 MySql 数据库中添加表情符号,但后来我通过更改排序规则并添加此 -> SET NAMES utf8mb4;
在我之前的插入查询之前查询解决了这个问题,但现在我无法获得最后一个从中插入 id。我应该怎么做才能插入表情符号以及从中获取最后插入的 ID。
这是我的代码。
public static JSONObject emoji(String comment) {
JSONObject json = new JSONObject();
Connection con = null;
PreparedStatement stmt = null;
String newInsertId = "";
try {
BasicDataSource bds = DBConnection.getInstance().getBds();
con = bds.getConnection();
String query = "SET NAMES utf8mb4; insert into emojis set message = '" + comment + "';";
stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
if (stmt.executeUpdate() > 0) {
json.put("success", 1);
}
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
newInsertId = rs.getString(1); //giving empty values cause of that SET NAMES utf8mb4; query
}
System.out.println(newInsertId); //empty
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
DbUtils.close(con);
DbUtils.close(stmt);
} catch (Exception e) {
e.printStackTrace();
}
}
return json;
}
最佳答案
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//参数2最好写上,虽然Mysql不写也能获取但是不代表别的数据库可以做到
ps.executeUpdate();
rs = ps.getGeneratedKeys();
int id = 0;
if (rs.next())
id = rs.getInt(1);
return id;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
—————————————————————————————————————————————— ————————
Focus on this 'Statement.RETURN_GENERATED_KEYS'
关于java - 当我将 SET NAMES 添加到我的插入语句时,将新插入的 id 作为空字符串获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56356273/