MySQL 如何正确插入多个表?

标签 mysql jdbc insert

如果我有这样的输入文件:

US, P1, AgriZone, H, 1000, 1200, 1101, 1210
US, P2, ArgiZone, L, 120, 122, 345, 566
MX, Q4, FarmOne, H, 1120, 2200, 1111, 2345

我有以下表格

Tables In SQLFiddle

我的问题:如何将这些记录正确插入数据库(考虑到一行落入多个表)?如何确保只添加唯一的表列?上面的示例 Agrizone 只需要表 Farm 中的一个条目?像这样插入时,这里的典型方法是什么?

 try
      {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection(
            "jdbc:mysql://" + this.getServer() + "/" + this.getDatabase(),
            user, password);

        Statement s1 = (Statement) con.createStatement();
        s1.executeUpdate("INSERT INTO" ??);

        con.close();

      }
  Catch(Exception blah)   

如何管理此类插入,确保 PK 和 FK 设置正确?

非常感谢 stackoverflow 社区!

最佳答案

对你的数据库表实现约束

  • 例如农场表中的 FARM_TITLE 应该是唯一的(不可能插入两次“Argizone”)

  • 使用外键将表相互链接起来。这保证您将能够重建一行文件,例如:US, P1, AgriZone, H, 1000, 1200, 1101, 1210 已被“拆分”成多个表

-使用事务:这样你就可以在更多的表上做更多的插入语句。如果插入失败,回滚事务,这样您就不会在数据库中“部分”插入一行文件:

 try{
   con.setAutoCommit(false);
   //do the multiple queries

   con.commit()
}
catch(Exception e) {
   con.rollback();
}

带有 sql 插入行的伪代码:US, P1, AgriZone, H, 1000, 1200, 1101, 1210

假设 US 是一个原点,还没有在表原点中,所以首先插入原点:

  //this is pseudo code that insert into db table and retreive the id inserted. ID shoul be primary key and autoincrement
 int origin_id = execute( INSERT INTO ORIGIN(ORIGIN_NAME) values ("US");

 //now we insert the P1 stock. Again STOCK_ID primary key auto inc
 int stock_id = execute( INSERT INTO STOCK(ORIGIN_ID, STOCK_TITLE) values (origin_id, "P1");

 //now fill table FARM
 int farm_id = execute (INSERT INTO FARM(STOCK_ID, FARM_TITLE, SIZE, FARM_COMPNENTS) values (stock_id,"Agrizone","H","100");

 //finally a cycle to insert in GATE suppose we have n entries in this case (1200, 1101, 1210). I image to have an array
 for(int i =0; i<n; i++)
     INSERT INTO GATE (FARM_ID, FARM_COMPONENTS) values (farm_id,value[i]);

关于MySQL 如何正确插入多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9929301/

相关文章:

python - 使用 Flask 连接 MySQL 时出现 500 Internal Server Error

java - 如何从 java 应用程序访问数据库而无需在 xampp 上外部放置 mysql 服务器

java - mysql主从复制问题: Cannot create PoolableConnectionFactory

arrays - Swift 数组随机插入和删除非常慢

php - 从复选框将多个值存入 MySQL

php - mysql select查询问题where id in ()

php - IPv4 地址的 mySQL 长度(INT 字段类型)

mysql - 从主 id 中选择相关 id 和映射值

mysql - Tomcat JDBC MySQL ClassNotFoundException 异常

mysql - INSERT 然后 SELECT 插入的行