我有两个表addstudent和parent,它们的主键分别与sid和Sid (学生ID)相同。我使用phpmyadmin。
我正在向单个表单输入值,但是应该将值分别插入这两个表中。这意味着将学生详细信息放入addstudent表中,将监护人详细信息放入parent表中。
我找到了一些带有事务处理的PHP代码:
String sql = "INSERT INTO addstudent (sid, first_name, last_name) VALUES
(no, fname, lname) ";
String q = "INSERT INTO parent (Sid, fathername,mothername)
VALUES (Sid,fn,mn)";
$result = mysqli_multi_query($conn, $sql);
if ($result) {
$verify=1;
}
else{
$verify=0;
}
echo $verify;
mysqli_close($conn);我需要知道的是:代码的$verify部分的目的是什么?
我使用Java编程语言。我需要一个事务来处理这个吗?或者我该如何处理这件事?
发布于 2015-08-22 02:23:33
如果第一条语句失败,mysqli_multi_query将返回false。因此,在这种情况下,$result将为false,因此$verify = 0,这表明出了问题。
使用事务:如果您有多个查询,并且其中一个查询失败(无论原因如何),那么您可以将数据库回滚到其以前的状态。
例如:您有一个只有一行数据的表。您想要插入另外两行。第一次插入成功,但第二次插入失败。现在,如果您使用transaction,您可以回滚数据库(现在是神奇的部分->),这样您就又有了一行。
发布于 2015-08-21 22:28:44
在您的示例中,$verify仅用于显示第一个查询是否成功。
查看有关PDO和事务的PHP文档。下面的例子非常符合你的用例。
http://php.net/manual/en/pdo.transactions.php
来自链接页面的示例:
<?php
try {
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
values (23, 50000, NOW())");
$dbh->commit();
} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>JDBC事务的Java文档:https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html
Java code example from the linked site:
public void updateCoffeeSales(HashMap<String, Integer> salesForWeek)
throws SQLException {
PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
if (updateSales != null) {
updateSales.close();
}
if (updateTotal != null) {
updateTotal.close();
}
con.setAutoCommit(true);
}
}https://stackoverflow.com/questions/32141681
复制相似问题