-2

我要存储以下数据是mysql数据库如何编写jdbc程序来存储以下数据

我有下表

message(messageid, message_heading ,message_data)
msgTag(tagid,tag,messageid)

我有 fowwing 数据 你好,你好吗(消息标题)

你好,你好吗....我很好(message_data)

标签-> 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);
}
}

我想更改以下代码,以便将多个标签存储在与一条消息相关的表中,并且应该保持事务控制。

4

1 回答 1

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();
    }
  }
}
于 2013-02-06T07:57:10.723 回答