为什么预备语句不会将数据插入数据库表?
import java.sql.*;
public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "java";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
PreparedStatement pst;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
conn.setAutoCommit(false);
String sql = "INSERT INTO test (url) values(?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "teast.com");
statement.executeUpdate();
statement.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:9)
因为您明确禁用了自动提交:
conn.setAutoCommit(false);
默认情况下,JDBC将自动提交隐式创建的任何事务。
禁用自动提交后,您需要显式提交,例如
statement.executeUpdate();
conn.commit();