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 有三个字段

 private String USERNAME;//跟数据库中字段名称不用要求大小写一样
 private String age;//数据库类型和java类型没有关系
 private int age1;//多出来字段会被赋予基本类型的默认值
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 增删改查例子的更多相关文章

  1. spring boot2+jpa+thymeleaf增删改查例子

    参考这遍文章做了一个例子,稍微不同之处,原文是spring boot.mysql,这里改成了spring boot 2.Oracle. 一.pom.xml引入相关模块web.jpa.thymeleaf ...

  2. 初次尝试PHP——一个简单的对数据库操作的增删改查例子

    第一次学习PHP,很多人说PHP是最好的语言,学习了一点点,还不敢说这样的话,不过确实蛮好用的. 做了一个简单的对数据库的增删改查的操作,主要是将四种操作写成了独立的函数,之后直接调用函数.以下是代码 ...

  3. JSP的一个增删改查例子和总结

    总结的几点: 1.在jsp中注意<%! %>声明代码块中的变量只会在项目开始的时候第一次运行jsp的时候执行一遍,有点类似于java类中的static代码块,所以如果是会改变的值不应该声明 ...

  4. 用liferay实现的增删改查例子-book管理系统

    liferay 这个框架是一个开源的项目,大家可以修改源代码,来实现自己的需求.但是关于liferay的开发资料中文的很少关于liferay的基础知识,大家可以百度学习一下,再来看下边的例子 首先需要 ...

  5. MVC增删改查例子

    一.显示用户列表1.新建UserInfoController控制器 public ActionResult Index() { DataTable table = SQLHelper.ExecuteR ...

  6. Redis:五种数据类型的简单增删改查

    Redis简单增删改查例子 例一:字符串的增删改查 #增加一个key为ay_key的值 127.0.0.1:6379> set ay_key "ay" OK #查询ay_ke ...

  7. 一个在ASP.NET中利用服务器控件GridView实现数据增删改查的例子

    备注:这是我辅导的一个项目开发组的一个例子,用文章的方式分享出来,给更多的朋友参考.其实我们这几年的项目中,都不怎么使用服务器控件的形式了,而是更多的采用MVC这种开发模式.但是,如果项目的历史背景是 ...

  8. dbutils中实现数据的增删改查的方法,反射常用的方法,绝对路径的写法(杂记)

    jsp的三个指令为:page,include,taglib... 建立一个jsp文件,建立起绝对路径,使用时,其他jsp文件导入即可 导入方法:<%@ include file="/c ...

  9. MySQL数据库学习笔记(十二)----开源工具DbUtils的使用(数据库的增删改查)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

随机推荐

  1. Prism 4 文档 ---第3章 管理组件间的依赖关系

     基于Prism类库的应用程序可能是由多个松耦合的类型和服务组成的复杂应用程序,他们需要根据用户的动作发出内容和接收通知进行互动,由于他们是松耦合的,他们需要一种方式来互动和交流来传递业务功能的需求. ...

  2. wxpython的简单的应用

    import wximport wx.xrc import pandas as pd from conf.env import * # 允许选择的文件wildcard = "Python s ...

  3. SpringXML方式配置bean的集合注入:list,map,properties

    新建一个bean,设置相应的集合属性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class Collecti ...

  4. node csrf 防御 待续

    csrf 防御 token 与 ajax 主要是在cookie添加随机数, 因为攻击者 无法访问第三方网站的 cookie,  加上httponly, 即使是xss也无法访问了 也可以在页面上嵌入一个 ...

  5. CUDA Samples: ripple

    以下CUDA sample是分别用C++和CUDA实现的生成的波纹图像,并对其中使用到的CUDA函数进行了解说,code参考了<GPU高性能编程CUDA实战>一书的第五章,各个文件内容如下 ...

  6. 深度学习(六十六)生成模型、最大化似然、KL散度

  7. artDialog的使用

    用法一:github上下载包:https://github.com/aui/artDialog                seajs方法使用 <!doctype html> <h ...

  8. JAVA多线程----用--进阶--》网络编程1

    http://www.cnblogs.com/springcsc/archive/2009/12/03/1616413.html 一个服务器端一般都需要同时为多个客户端提供通讯,如果需要同时支持多个客 ...

  9. C函数说明

    输入函数scanf_s()   比如:char d[20];写成scanf_s("%s",d,20); 输出函数printf()      比如:printf("hell ...

  10. BZOJ1098 POI2007 办公楼biu 【链表+bfs】

    Description FGD开办了一家电话公司.他雇用了N个职员,给了每个职员一部手机.每个职员的手机里都存储有一些同事的电话号码.由于FGD的公司规模不断扩大,旧的办公楼已经显得十分狭窄,FGD决 ...