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. py-faster-rcnn:在windows上配置

    0.先说一下本机配置 opencv2+cuda7.5+cudnn+anaconda,这些基础的之前都是配置好了的,python环境建议使用anaconda,用到的库基本都有了,好像没有easydict ...

  2. 【2018多校第一场】hdu6308-Time Zone(日期)

    Problem Description Chiaki often participates in international competitive programming contests. The ...

  3. HDU 5875 Function (线段树+gcd / 单调栈)

    题意:给你一串数a再给你一些区间(lef,rig),求出a[lef]%a[lef+1]...%a[rig] 题解:我们可以发现数字a对数字b取模时:如果a<b,则等于原数,否则a会变小至少一半. ...

  4. New Concept English there (4)

    20w/m These days, people who do manual work often receive far more money than people who work in off ...

  5. Python中函数练习

    练习1:编写一个函数,接收一个字符串参数,返回一个元组(第一个元素为大写字母的个数,第二个元素为小写字母的个数) 解析:  练习二:编写函数,计算字符串匹配的准确率(orginStr为原始内容,use ...

  6. Shell 批量搜索关键词并保存结果到文件中(数组、循环)

    #!/bin/bash keywords=("不需要" "不用谢谢" "xxx" "xxx") for var in $ ...

  7. pdf 数据流解析

     根据这个解释可以认为,/CCITTFaxDecode应该指单色图像(每个像素占8位?还是1位),FlateDecode 指文字或者矢量图片(png) 参考论文:http://www.doc88.co ...

  8. times(NULL) Segmentation fault

    ****************************************************************************** * times(NULL) Segment ...

  9. WEB服务器都在做哪些工作?

    作为WEB开发人员,我们肯定应该要知道WEB服务器都在做哪些工作,这里简单列举一下,有时间然后详细说明. (1)建立连接——接受一个客户端连接. (2)接收请求——从网络中读取一条 HTTP 请求报文 ...

  10. C/C++比较容易搞混的一些写法

    #include <stdio.h> int main() { int a = 101; char ch = *(char *)&a; //*(char *)&a:含义就是 ...