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. Highcharts 散点图

    Highcharts 散点图 配置 chart 配置 配置 chart 的 type 为 'scatter' .chart.type 描述了图表类型.默认值为 "line". ch ...

  2. 优先队列PriorityQueue实现 大小根堆 解决top k 问题

    转载:https://www.cnblogs.com/lifegoesonitself/p/3391741.html PriorityQueue是从JDK1.5开始提供的新的数据结构接口,它是一种基于 ...

  3. Spring入门1. IoC入门实例

    Spring入门1. IoC入门实例 Reference:Java EE轻量级解决方案——S2SH 前言: 之前学习过关于Spring的一点知识,曾经因为配置出现问题,而总是被迫放弃学习这些框架技术, ...

  4. SpringXML方式配置bean的自动装配autowire

    Spring的自动装配,也就是定义bean的时候让spring自动帮你匹配到所需的bean,而不需要我们自己指定了. 例如: User实体类里面有一个属性role 1 2 3 4 5 6 7 publ ...

  5. kibana安装

    kibana,ELK中的K,主要为ES提供界面化操作,据说还是比较炫的,今天安装5.5.2版本进行尝试一把. 安装过程不难,简单的配置了一下端口和IP即可,难度不大. config下的kibana.y ...

  6. PHP use

    PHP 7 use 语句  PHP 7 新特性 PHP 7 可以使用一个 use 从同一个 namespace 中导入类.函数和常量: 实例 实例 // PHP 7 之前版本需要使用多次 use us ...

  7. resultMap的使用

    1)属性 id:resultMap的唯一标识 type:Java实体类 2)子元素 id 一般对应数据库中该行的主键id,设置此项可提高MyBatis性能 result 映射到JavaBean的某个“ ...

  8. ffmpeg jpeg图片播放失败之问题排查

    播放jpeg时,avformat_find_stream_info出现以下问题,排查: [jpeg_pipe @ 0x146a80] Could not find codec parameters f ...

  9. (转)MapReduce Design Patterns(chapter 7 (part 2))(十四)

    External Source Input Pattern Description 这种模式不从hdfs加载数据,而是从hadoop以外系统,例如RDB或web service加载. Intent 想 ...

  10. [Linux] 输出文件的指定行

    1.获取第k行(以k=10为例) 要注意的是,如果文件包含内容不足10行,应该不输出. # Read from the file file.txt and output the tenth line ...