我有下表
message(messageid, message_heading ,message_data)
msgTag(tagid,tag,messageid)
我有数据显示 你好,你(消息标题)
你好,你好......我很好(message_data)
tags-> abc,rst def,mer,hat
我想在上面提到的表格中存储以上数据。如何做到这一点。
它还必须使用事务控制
我完成了以下编码
PreparedStatement msg = null;
PreparedStatement tags = null;
String querymsg =
insert in to msg value(?,?,?);
String querytags =
insert in to msg value(?,?,?);
try {
con.setAutoCommit(false);
insertmsg = con.prepareStatement(querymsg);
inserttags = con.prepareStatement(querytags);
insertmsg.setString(1,msgid);
insertmsg.setString(2,message_heading);
insertmsg.setString(3,message_data);
insertmsg.executeUpdate();
inserttags.setString(1,tagid);
inserttags.setString(2,tag);
inserttags.setString(3,messageid);
inserttags.executeUpdate();
}
} catch (SQLException e ) {
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
if (insertmsg != null) {
insertmsg.close();
}
if (inserttags != null) {
inserttags.close();
}
con.setAutoCommit(true);
}
}
我想更改以下代码,以便在表中存储多个标记 与一条消息相关,并应保持事务控制。
答案 0 :(得分:0)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/databaseName";
String username = "username";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "insert into message values(?, ?, ?)";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 5); // set input parameter 1
pstmt.setString(2, "head5"); // set input parameter 2
pstmt.setString(3, "data5"); // set input parameter 3
pstmt.executeUpdate(); // execute insert statement
pstmt = conn.prepareStatement("insert into msgtag values(?, ?, ?)"); // create a statement
pstmt.setInt(1, 55); // set input parameter 1
pstmt.setString(2, "tag5"); // set input parameter 2
pstmt.setInt(3, 5); // set input parameter 3
pstmt.executeUpdate(); // execute insert statement
} catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
}