JDBC JdbTemplate&NamedParameterJdbcTemplate(Spring工具类)

使用该工具类需要从spring开发包中导入spring.jar和commons-logging.jar,这个模板是线程安全的。

JdbcTemplate:

public class JdbcTeSQLmplateTest {

static ​JdbcTemplate​ jdbc = new JdbcTemplate(JdbcUtils.getDataSource());

/**

* @param args

*/

public static void main(String[] args) {

Umysql索引ser user = findUser("zhangsan");

// System.out.println("user:" + user);

// System.out.println("users:" + findUsmysql增删改查语句ers(3));

// System.out.println("user count:" + getUser数据库设计Count());

// System.out.println(主键只能有一个吗"user name:" + getmysql数据库UserName(1));

System.out.println("data:" + get主键和外键的区别Data(1));

}

static int addUser(final User user) {

jdbc.execute(new ConnectionCallback() {//想在插入的时候取主键,回调

public Object doInConnection(Connection c申请了营业执照可以不经营吗on) throws SQLExce舍曲林ption主键只能有一个吗, DataAccessExceptimysqlon {

S数据库是什么tring sql = "insert into user(name,birthday, money) values (主键和外键的区别?,sql数据库?,?) ";mysql数据库

PreparedStatement ps = con.prepareSta舍曲林tement(sql,

Statement.RETURN_GENERATED_KE主键索引YS);

ps.setStr盛气凌人的意思ing(1, user.getName());

ps.setDa孙侨潞te(2, new java.sql.Date(user.getBirthday().getmysql安装Time()));

ps.setFloat(3, user.getMoney());

ps.executeUpdate();

Rmysql安装esultSet rs = ps.getGene数据库查询语句ratedKeys();

if (rs.next())

user.setId(rs.getInt(1));

retu数据库系统的核心是rn null;

}

});

return 0;

}

static Map getData(int id) {

String sql = "select id as userId, name, money, birt数据库技术hday from user where id="

+ id;

return jdbc.queryForMap(sql);

}

static String getUserName(int id) {

String sql = "select name from user where id=" + id;

Obj主键和外键ect name = jdbc.queryForObject(sql, Stri主键约束ng数据库系统工程师.class);

return (String) name;

}

static int getUserCount() {

String sql = "select count(*) from user";

return jdbc.queryForInt(sql);//直接把结果返回成int型,也可以查询最大值平均孙侨潞值之类的

}

static List findUsers(int id) {

String sql = "select id, name, money, birthday from user where imysql安装d<?";

Object[] args = new Object[] { id };

int[] argTypes = new int[] { Types.INTEGER };

List users = jdbc.query(sql, args, argTypes, new BeanPropertyRowMapmysql面试题per(

User.class));//查询结果是多条舍曲林记录

return users;

}

static User findUser(String name) {

String sql = "select id, name, money, birthday from user where name=?mysql安装";

Object[] args = new Object[] { name };

Object user = jdbcmysql安装.queryForObject(sql, args, new BeanPropertyRowMapper(

User.class));主键的作用//queryForObject查询如果查不到数据或者多于一条数据会报错

return (User) user主键约束;

}

stamysql安装配置教程tic User findU主键的建立有几种方法ser1(String name) {

String sql = "select id, name, money, birt苏卿陆容渊hday from user where name=?";

Object[] args = n宋庆玲ew Object[] { name };

Object user = jdbc.queryForObject(sql, args, new RowMapper() {

public Object ma申请了营业执照可以不经营吗pRow(ResultSet rs, int rowNum) throws SQLException {主键的作用

User user = new User();

user.setId(rs.getIntmysql索引("id"));数据库系统的核心是

user数据库.s数据库etName(rs.getString("name"));

user.setMoney(rs.gmysql增删改查语句etFloat("数据库系统概论第五版课后答案money"数据库管理系统));

user.setBirthday(rs.getDate("birthday"));

retu主键的作用rn user;

}

});

return (User) user;

}

}

NamedP主键可以为空吗arameterJdbcTemplate​ :包含​JdbcTemplate的功能,特点是可以解析sql语句中的非?参数,而且主键和外键的区别可以直接用sql去匹配bean中的属性。

public class NamedJdbcTemplate {

stati舍曲林c ​NamedParameterJdbcTemplate​ named = new NamedParameterJdbcTemplate(

JdbcUtils.getDataSource());

/**

* @param args

*/

public static void main(String[] arg主键索引s) {

User user = new User();

user.setMoney(10);

user.setId(2);

System.out.printl数据库管理系统n(findUser宋庆玲1(usmysql安装er));

}

static void addUser(User user) {

String sql = "insert into user(name,birthday, money) values (:name,:birthday,:money) ";

SqlParameterSource ps = new ​BeanPropertySqlPa苏卿陆容渊免费阅读rameterSource​(user); //使用bemysql数据库命令大全an来设置sql中的参数

KeyHo主键约束lder keyH数据库是什么older = new GeneratedKey数据库系统工程师HSQLolder();

named.update(sql, ps, keyHolder); //获取主键

int id = keyHolder.getKey().intValue();

user.smysql数据库etId(id);

Map map = keyHolder.getKeys(); //如果主数据库管理系统键是多个,可以用该方法获取成Map映射

}

static User findUser(User user) {

String sql = "select id, name, money, birthday from user "

+ "w数据库管理系统here money > :m and id < :id";

Map params = new HashMap();

// params.put("n", user.getName());

params.put("m", user.getMoney());

params.pmysql创建表ut("id"数据库原理及应用, user.getId()); //使用Map来设置sql的参数

Objectmysql u = n帅气撩人高冷动漫男头amed.queryForObject(sql, par主键约束ams, new BeanP帅气撩人高冷动漫男头ropertyRowMapper(

User.mysql面试题class)); //第三个参数是一个映射器,将获取的数据映射给Bean

return (User) u;

}

static User findUse孙侨潞r1(User user) {

String sql = "select id, name, money, birthday from user "

+ "where money > :money and id &mysql面试题lt; :id";

SqlParame主键的作用terSource ps = new Be主键anProp主键ertySqlParameterSource(user);

Object u = named.queryForObject(sql, ps, new BeanP主键和外键ropertyRowMapper(

User.class));

return (User) u;

}

}

SimpleJdbcTemplate:在前主键可以为空吗两者基础上支持了可变参数和泛型

public class SimpleJdbcTemplateTest {

static SimpleJdbcTemplate simple = new Simple宋庆玲JdbcTemplate(JdbcUtils

.getDataSource());

static User find(String name) {

String sql = "select id, name, money, birthday from user where name=? and monemysql增删改查语句y &g苏卿陆容渊免费阅读t; ?";

Umysqlser user = simple.queryForObject(sql,

ParameterizedBeanPropertyRowMapper.newInstanc数据库是什么e(User.class),

name, 100f);

return user;

//simple.getNamed苏卿陆容渊ParameterJ帅气撩人高冷动漫男头dbcOperations().update(sql,paramSource,keyHolder);先获取NamedJd主键bcTemplate模板主键怎么设置,再获取主键

//siSQLmple.getJdbcOpe主键是什么意思rations()获取Jdbc主键的建立有几种方法Te主键和外键mplate

}

}

上面代码引用的自定义工具类的代码:

public final class Jdbc舍曲林Utils {

private static String url = "jdbc:mysql://local主键的建立有几种方法host:3306/jdbc";

private static String user = "root";

pri主键的作用vate static Strmysql索引ing password = "";

private static DataSource myDmysql安装ataSource = null;

private JdbcUtils() {

}

static {

try {

Class.forNam孙侨潞e("com.mysql.jdb主键的建立有几种方法c.Driver");

// myDataSource = new MyDataSource2();

Properties prop = new Properties();

// promysql安装配置教程p.setProperty("driverClassName", "com.m主键ysq数据库l.jdbc.Driver");

// pmysql安装rop.setProperty("user", "usemysql安装r");

InputStream is = JdbcUtils.class.getClassLoader()

.getResourceAsStream("dbcpconfig.properties");数据库技术

prop.load(is);

myDataSource = BasicDataSoumysql安装配置教程rceFacsql数据库tory.createDataSource(prop);

} catch (Exception e) {

throw new ExceptionInInitializerError(e);

}

}

public static DataSource getDataSource() {mysql密码忘记了怎么办

return m主键的作用yDataSource;

}

public static Connection getConnection() throw主键只能有一个吗s SQLException {数据库系统

// return DriverManager.getConnection(url, user, password);

return myDataSourmysqlce.getConnection();

}

public static void free(ResultSet rs, Statement st, Connection conn) {

try {

if (rs != null)

rs.close();

} catcmysqlh (SQLExcept主键和外键io苏卿陆容渊免费阅读n e) {

e.printStackTrace();

} f数据库是什么inally {

try {

if (st != null)

st.close();

} catch (SQLException e) {

e.printStackTrace();

} finally {

i主键f (conn != null)

try {

conn.close(mysql密码忘记了怎么办);

// myDataSourcmysql安装配置教程e.free(conn);

} catch (Exception e) {

e.printStackT盛气凌人的意思race();

}

}

}

}

}