

应用实例
模拟经典的转账业务
首先创建一张account表,插入两条数据
CREATE TABLE ACCOUNT(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(32) NOT NULL DEFAULT '',
balance DOUBLE NOT NULL DEFAULT 0
)CHARACTER SET utf8;
INSERT INTO ACCOUNT VALUES(NULL,'马云',3000),(NULL,'马化腾',10000);
SELECT * FROM ACCOUNT;
package li.jdbc.transaction_;
import li.jdbc.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 演示JDBC中如何使用事务
*/
public class Transaction_ {
//没有使用事务
@Test
public void noTransaction() {
//操作转账业务
//1.得到连接
Connection connection = null;
//2.组织sql语句
String sql = "update account set balance=baLance-100 where id=1";
String sql2 = "update account set balance=baLance+100 where id=2";
//3.创建PreparedStatement对象
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();//在默认情况下,connection默认自动提交
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate(); //执行第一条sql
int i = 1 / 0;//抛出异常--模拟异常可能--可以看到出现异常状态之后的语句没有执行
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();//执行第二条sql
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
//使用事务来解决
@Test
public void useTransaction() {
//操作转账业务
//1.得到连接
Connection connection = null;
//2.组织sql语句
String sql = "update account set balance=baLance-100 where id=1";
String sql2 = "update account set balance=baLance+100 where id=2";
//3.创建PreparedStatement对象
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();//在默认情况下,connection默认自动提交
//将connection设置为不自动提交
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate(); //执行第一条sql
int i = 1 / 0;//抛出异常
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();//执行第二条sql
//在这里提交事务
connection.commit();
} catch (Exception e) {
//如果在try里面出现了异常,就会进入catch语句,
// 这意味着我们可以在catch语句里面进行回滚,即撤销执行的SQL语句
System.out.println("执行发生了异常,撤销已执行的SQL");
try {
connection.rollback();//没有填写保存点就默认回滚到事务开始的状态
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
}
例子
user=root
password=123456
url=jdbc:mysql://localhost:3306/hsp_db02?rewriteBatchedStatements=true
driver=com.mysql.jdbc.Driver
首先创建测试表admin2
CREATE TABLE admin2(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) NOT NULL,
PASSWORD VARCHAR(32) NOT NULL );
SELECT COUNT(*) FROM admin2;
测试程序:
package li.jdbc.batch_;
import li.jdbc.utils.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 演示java的批处理
*/
public class Batch_ {
//传统方法,添加5000条数据到admin2
@Test
public void noBatch() throws Exception {
//获取连接
Connection connection = JDBCUtils.getConnection();
//sql
String sql = "insert into admin2 values (null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
preparedStatement.setString(1, "jack" + i);
preparedStatement.setString(2, "666");
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("传统的方式耗时:" + (end - start));
//关闭连接
JDBCUtils.close(null, preparedStatement, connection);
}
//使用批量方式添加数据--注意在配置文件添加参数?rewriteBatchedStatements=true
@Test
public void batch() throws Exception {
//获取连接
Connection connection = JDBCUtils.getConnection();
//sql
String sql = "insert into admin2 values (null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
preparedStatement.setString(1, "jack" + i);
preparedStatement.setString(2, "666");
//将SQL语句加入到批处理包中
preparedStatement.addBatch();
//当有1000条SQL时,再批量执行
if ((i + 1) % 1000 == 0) {//每满1000条时,就批量执行
preparedStatement.executeBatch();
//执行完就清空批处理包
preparedStatement.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println("批量方式耗时:" + (end - start));
//关闭连接
JDBCUtils.close(null, preparedStatement, connection);
}
}
在上述代码中,在preparedStatement.addBatch();语句旁打上断点,点击debug,点击step into
可以看到光标跳转到了如下方法:
public void addBatch() throws SQLException {
if (this.batchedArgs == null) {
this.batchedArgs = new ArrayList();
}
this.batchedArgs.add(new PreparedStatement.BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull));
}
第一次执行该方法时,会创建Arraylist类型的对象集合elementDate=>Object[],elementDate=>Object[]用来存放我们预处理的SQL语句。当elementDate满后,就按照1.5倍扩容
当添加到指定的值后,就会执行executeBatch();
批处理会减少我们发送SQL语句的网络开销,并且减少编译次数,因此效率提高了
1.5倍扩容:
事务:
事务底层是在数据库方存储SQL,没有提交事务的数据放在数据库的临时表空间。
最后一次提交是把临时表空间的数据提交到数据库服务器执行
事务消耗的是数据库服务器内存
批处理:
批处理底层是在客户端存储SQL
最后一次执行批处理是把客户端存储的数据发送到数据库服务器执行。
批处理消耗的是客户端的内存
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类
require"socket"server="irc.rizon.net"port="6667"nick="RubyIRCBot"channel="#0x40"s=TCPSocket.open(server,port)s.print("USERTesting",0)s.print("NICK#{nick}",0)s.print("JOIN#{channel}",0)这个IRC机器人没有连接到IRC服务器,我做错了什么? 最佳答案 失败并显示此消息::irc.shakeababy.net461*USER:Notenoughparame
考虑一下:现在这些情况:#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2我需要用其他字符串输出URL。我如何保证&符号不会被转义?由于我无法控制的原因,我无法发送&。求助!把我的头发拉到这里:\编辑:为了澄清,我实际上有一个像这样的数组:@images=[{:id=>"fooid",:url=>"http://
我有一个super简单的脚本,它几乎包含了FayeWebSocketGitHub页面上用于处理关闭连接的内容:ws=Faye::WebSocket::Client.new(url,nil,:headers=>headers)ws.on:opendo|event|p[:open]#sendpingcommand#sendtestcommand#ws.send({command:'test'}.to_json)endws.on:messagedo|event|#hereistheentrypointfordatacomingfromtheserver.pJSON.parse(event.d
我有一个ruby脚本可以打开与Apple推送服务器的连接并发送所有待处理的通知。我看不出任何原因,但当Apple断开我的脚本时,我遇到了管道损坏错误。我已经编写了我的脚本来适应这种情况,但我宁愿只是找出它发生的原因,这样我就可以在第一时间避免它。它不会始终根据特定通知断开连接。它不会以特定的字节传输大小断开连接。一切似乎都是零星的。您可以在单个连接上发送的数据传输或有效负载计数是否有某些限制?看到人们的解决方案始终保持一个连接打开,我认为这不是问题所在。我看到连接在3次通知后断开,我看到它在14次通知后断开。我从未见过它能超过14点。有没有人遇到过这种类型的问题?如何处理?
我的意思是之前建立的那个DB=Sequel.sqlite('my_blog.db')或DB=Sequel.connect('postgres://user:password@localhost/my_db')或DB=Sequel.postgres('my_db',:user=>'user',:password=>'password',:host=>'localhost')等等。Sequel::Database类没有名为“disconnect”的公共(public)实例方法,尽管它有一个“connect”。也许有人已经遇到过这个问题。我将不胜感激。 最佳答案
我有一个任务列表(名称、starts_at),我试图在每日View中显示它们(就像iCal)。deftodays_tasks(day)Task.find(:all,:conditions=>["starts_atbetween?and?",day.beginning,day.ending]end我不知道如何将Time.now(例如“2009-04-1210:00:00”)动态转换为一天的开始(和结束),以便进行比较。 最佳答案 deftodays_tasks(now=Time.now)Task.find(:all,:conditio
我有一个遗留数据库,我正在努力让ActiveRecord使用它。我遇到了连接表的问题。我有以下内容:classTvShow然后我有一个名为tvshowlinkepisode的表,它有2个字段:idShow、idEpisode所以我有2个表和它们之间的连接(多对多关系),但是连接使用非标准外键。我的第一个想法是创建一个名为TvShowEpisodeLink的模型,但没有主键。我的想法是,由于外键是非标准的,我可以使用set_foreign_key并进行一些控制。最后,我想说一些类似TvShow.find(:last).episodes或Episode.find(:last).tv_sho
我正在使用PostgreSQL9.1.3(x86_64-pc-linux-gnu上的PostgreSQL9.1.3,由gcc-4.6.real(Ubuntu/Linaro4.6.1-9ubuntu3)4.6.1,64位编译)和在ubuntu11.10上运行3.2.2或3.2.1。现在,我可以使用以下命令连接PostgreSQLsupostgres输入密码我可以看到postgres=#我将以下详细信息放在我的config/database.yml中并执行“railsdb”,它工作正常。开发:adapter:postgresqlencoding:utf8reconnect:falsedat