DBUtils 增删改查例子
sql
CREATE TABLE [dbo].[Person] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[userName] [nvarchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
[age] [int] NULL
) ON [PRIMARY]
GO
1:取得一行记录.DataSource
package com.x.test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.sql.DataSource;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
public class TEST01_getFirstRow
{
public static void main(String[] args) throws SQLException
{
TEST01_getFirstRow t = new TEST01_getFirstRow();
t.test();
}
private void test() throws SQLException
{
// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
ResultSetHandler<Object[]> h = new ResultSetHandler<Object[]>()
{
public Object[] handle(ResultSet rs) throws SQLException
{
if (!rs.next())
{
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Object[] result = new Object[cols];
for (int i = 0; i < cols; i++)
{
result[i] = rs.getObject(i + 1);
}
return result;
}
};
// Create a QueryRunner that will use connections from
// the given DataSource
JtdsDataSource dataSource = new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("DBtest");
dataSource.setUser("sa");
dataSource.setPassword("");
QueryRunner run = new QueryRunner(dataSource);
// Execute the query and get the results back from the handler
Object[] result = run.query("SELECT * FROM Person WHERE username!=?", h, "John Doe");
System.out.println("over");
}
}
2:取得一行记录,Connection
package com.x.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.sql.DataSource;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
public class TEST02_getFirstRow2
{
public static void main(String[] args) throws SQLException
{
TEST02_getFirstRow2 t = new TEST02_getFirstRow2();
t.test();
}
private void test() throws SQLException
{
// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
ResultSetHandler<Object[]> h = new ResultSetHandler<Object[]>()
{
public Object[] handle(ResultSet rs) throws SQLException
{
if (!rs.next())
{
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Object[] result = new Object[cols];
for (int i = 0; i < cols; i++)
{
result[i] = rs.getObject(i + 1);
}
return result;
}
};
// Create a QueryRunner that will use connections from
// the given DataSource
JtdsDataSource dataSource = new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("DBtest");
dataSource.setUser("sa");
dataSource.setPassword("");
Connection conn = DriverManager.getConnection(
"jdbc:jtds:sqlserver://localhost:1433/DBtest;", "sa", "");
QueryRunner run = new QueryRunner();
try
{
Object[] result = run.query(conn,
"SELECT * FROM Person WHERE userName!=?", h, "John Doe");
// do something with the result
System.out.println("over");
}
finally
{
// Use this helper method so we don't have to check for null
DbUtils.close(conn);
}
System.out.println("over");
}
}
3:添加/更新
package com.x.test;
import java.sql.SQLException;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import org.apache.commons.dbutils.QueryRunner;
public class TEST03_insertData
{
/**
* @param args
*/
public static void main(String[] args)
{
TEST03_insertData insert=new TEST03_insertData();
insert.test();
}
private void test()
{
JtdsDataSource dataSource=new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("DBtest");
dataSource.setUser("sa");
dataSource.setPassword("");
QueryRunner run = new QueryRunner( dataSource );
try
{
// Execute the SQL update statement and return the number of
// inserts that were made
int inserts = run.update( "INSERT INTO Person (userName,age) VALUES (?,?)",
"zhanghongjie", 122 );
// The line before uses varargs and autoboxing to simplify the code
// Now it's time to rise to the occation...
int updates = run.update( "UPDATE Person SET age=? WHERE username=?",
2, "zhanghongjie" );
// So does the line above
System.out.println("over");
}
catch(SQLException sqle) {
// Handle it
}
}
}
4:异步执行更新
package com.x.test;
import java.sql.SQLException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import org.apache.commons.dbutils.AsyncQueryRunner;
public class TEST04_asyncQueryRunner
{
public static void main(String[] args)
{
TEST04_asyncQueryRunner t = new TEST04_asyncQueryRunner();
t.test();
}
private void test()
{
JtdsDataSource dataSource = new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("DBtest");
dataSource.setUser("sa");
dataSource.setPassword("");
// ExecutorCompletionService<Integer> executor = new
// ExecutorCompletionService<Integer>(
// Executors.newCachedThreadPool());
AsyncQueryRunner asyncRun = new AsyncQueryRunner(dataSource, Executors
.newCachedThreadPool());
try
{
for (int i = 0; i < 10; i++)
{
System.out.println("over1");
}
// Create a Callable for the update call
Future futures = asyncRun.update(
"UPDATE Person SET age=? WHERE username=?", 120,
"zhanghongjie");
for (int i = 0; i < 10; i++)
{
System.out.println("over2");
}
System.out.println(futures.get());//如果有必要取得返回结果
for (int i = 0; i < 10; i++)
{
System.out.println("over3");
}
// Submit the Callable to the executor
// executor.submit(callable);
}
catch (Exception sqle)
{
// Handle it
}
// Sometime later (or in another thread)
// try
// {
// // Get the result of the update
// Integer updates = executor.take().get();
// System.out.println("over");
// }
// catch (Exception ie)
// {
// // Handle it
// }
}
}
这个官方的例子错了。
5:动态映射类取得一条记录
注意:Person.java 有三个字段
package com.x.test;
import java.sql.SQLException;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.x.vo.Person;
public class TEST05_getByclz
{
public static void main(String[] args)
{
TEST05_getByclz t = new TEST05_getByclz();
t.test();
}
private void test()
{
JtdsDataSource dataSource = new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("DBtest");
dataSource.setUser("sa");
dataSource.setPassword("");
QueryRunner run = new QueryRunner(dataSource);
// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
ResultSetHandler<Person> h = new BeanHandler<Person>(Person.class);
// Execute the SQL statement with one replacement parameter and
// return the results in a new Person object generated by the
// BeanHandler.
try
{
Person p = run.query("SELECT * FROM Person WHERE id=?", h, "1");
System.out.println(p);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
6:动态映射类取得List
package com.x.test;
import java.sql.SQLException;
import java.util.List;
import net.sourceforge.jtds.jdbcx.JtdsDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.x.vo.Person;
public class TEST06_getListByclz
{
public static void main(String[] args)
{
TEST06_getListByclz t = new TEST06_getListByclz();
t.test();
}
private void test()
{
JtdsDataSource dataSource = new JtdsDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("DBtest");
dataSource.setUser("sa");
dataSource.setPassword("");
QueryRunner run = new QueryRunner(dataSource);
// Use the BeanHandler implementation to convert the first
// ResultSet row into a Person JavaBean.
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class);
// Execute the SQL statement with one replacement parameter and
// return the results in a new Person object generated by the
// BeanHandler.
try
{
List<Person> p = run.query("SELECT * FROM Person ", h);
System.out.println(p);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
转自:http://www.open-open.com/lib/view/open1331524877984.html
DBUtils 增删改查例子的更多相关文章
- spring boot2+jpa+thymeleaf增删改查例子
参考这遍文章做了一个例子,稍微不同之处,原文是spring boot.mysql,这里改成了spring boot 2.Oracle. 一.pom.xml引入相关模块web.jpa.thymeleaf ...
- 初次尝试PHP——一个简单的对数据库操作的增删改查例子
第一次学习PHP,很多人说PHP是最好的语言,学习了一点点,还不敢说这样的话,不过确实蛮好用的. 做了一个简单的对数据库的增删改查的操作,主要是将四种操作写成了独立的函数,之后直接调用函数.以下是代码 ...
- JSP的一个增删改查例子和总结
总结的几点: 1.在jsp中注意<%! %>声明代码块中的变量只会在项目开始的时候第一次运行jsp的时候执行一遍,有点类似于java类中的static代码块,所以如果是会改变的值不应该声明 ...
- 用liferay实现的增删改查例子-book管理系统
liferay 这个框架是一个开源的项目,大家可以修改源代码,来实现自己的需求.但是关于liferay的开发资料中文的很少关于liferay的基础知识,大家可以百度学习一下,再来看下边的例子 首先需要 ...
- MVC增删改查例子
一.显示用户列表1.新建UserInfoController控制器 public ActionResult Index() { DataTable table = SQLHelper.ExecuteR ...
- Redis:五种数据类型的简单增删改查
Redis简单增删改查例子 例一:字符串的增删改查 #增加一个key为ay_key的值 127.0.0.1:6379> set ay_key "ay" OK #查询ay_ke ...
- 一个在ASP.NET中利用服务器控件GridView实现数据增删改查的例子
备注:这是我辅导的一个项目开发组的一个例子,用文章的方式分享出来,给更多的朋友参考.其实我们这几年的项目中,都不怎么使用服务器控件的形式了,而是更多的采用MVC这种开发模式.但是,如果项目的历史背景是 ...
- dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)
jsp的三个指令为:page,include,taglib... 建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可 导入方法:<%@ include file="/c ...
- MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)
[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...
随机推荐
- cookie和localstorage sessionStorage的概念、区别、使用场景
本文分为三大板块: 1 webStorage的概念 2 cookie/localStorage/sessionStorage的介绍 3 三者之间的共同点和区别 **所有代码引用均来自 作者:OBKor ...
- hdu1151
题解: 二分图边覆盖 n-最大匹配 代码: #include<cstdio> #include<cmath> #include<algorithm> #includ ...
- 用国内镜像源pip加速安装模块
记住,如果使用了virtualenv,一定要先workon进入虚拟环境再执行包安装命令. pip install -i https://pypi.douban.com/simple/ 模块名(如:dj ...
- 2017-2018-2 20165202 实验三《敏捷开发与XP实践》实验报告
一.实验报告封面 二.实验内容 XP基础 XP核心实践 相关工具 三.实验步骤 (一)格式化代码 实验要求: 在IDEA中使用工具(Code->Reformate Code)把下面代码重新格式化 ...
- Linux下的软件的安装
一.yum相关介绍及命令 [1] 用来管理软件的一个命令.通过该命令完成对软件的下载.卸载等操作. [2] 命令:(必须在yum搭建成功后才能正常运行) yum clean all 清楚 ...
- wxWidgets的配置
参考 :http://www.codeproject.com/Articles/11515/Introduction-to-wxWidgets 我是将D:\wxWidgets-3.0.1,中 编译过 ...
- three.js入门系列之导入拓展类
先来看一下three.js包的目录结构: 我们使用的时候,可以一次性import所有的功能,也可以按需引入,全依赖three.module.js这个文件对three.js的功能作了模块化处理: 但是, ...
- Chrome调试javacript禁止缓存
/********************************************************************* * Chrome调试javacript禁止缓存 * 说明: ...
- Python3 字符串操作
截掉指定字符串 # 截掉指定字符串 string.strip("what you want to delete") #截掉字符串左边的空格 string.lstrip() #截掉字 ...
- vue-router(二)后代路由
关键字:router,children ,router-link,router-view,router-link-active 先理解什么是children? 后代路由为某路由中用到router-vi ...