關(guān)于jdbctemple的快速用法
項(xiàng)目有些時(shí)候需要自己寫個(gè)demo然后批量導(dǎo)入數(shù)據(jù)亚再,但是這部分代碼并不能合并到主干代碼上面(src目錄下的main),一般只能放到(src目錄下的test)
這個(gè)時(shí)候?qū)懪渲梦募蜎]有必要,而且還得配置半天,這種一次性配置通常不考慮寫配置文件。
我們就可以直接用datasource構(gòu)造一個(gè)jdbctemplate
datasource構(gòu)造的時(shí)候賦四個(gè)值
數(shù)據(jù)庫(kù)URL隶垮,驅(qū)動(dòng)名公般,用戶名,密碼
然后就可以直接使用jdbctemplate對(duì)象直接操作數(shù)據(jù)庫(kù)了
DataSource dataSource=new DataSource();
dataSource.setDriverClassName("");
dataSource.setPassword("");
dataSource.setUrl("");
dataSource.setUsername("");
JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
jdbcTemplate.update(sql,new Object[]{});
注意datasourse也有setName這個(gè)方法仰坦,千萬(wàn)不搞錯(cuò)了,不然就會(huì)非法用戶名跟密碼
不過(guò)這里會(huì)有一個(gè)問題计雌,建立的連接太多悄晃,或出現(xiàn)超時(shí)并且斷開連接,這個(gè)時(shí)候就要進(jìn)行詳細(xì)的配置比較好
Exception in thread "main" org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: The Network Adapter could not establish the connection
下面附上詳細(xì)配置的代碼
dataSource.setDriverClassName("");
dataSource.setPassword("");
dataSource.setUrl("");
dataSource.setUsername("");
dataSource.setInitialSize(20);
dataSource.setMaxIdle(30);
dataSource.setMinIdle(10);
dataSource.setMaxActive(50);
dataSource.setMaxWait(3000);
dataSource.setLogAbandoned(true);
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeout(180);
dataSource.setTestWhileIdle(true);
dataSource.setValidationQuery("select 1 from dual");
dataSource.setTestOnBorrow(true);
dataSource.setMinEvictableIdleTimeMillis(600000);
dataSource.setTimeBetweenEvictionRunsMillis(300000);
設(shè)置完之后數(shù)據(jù)庫(kù)就能正常連接凿滤,直到程序結(jié)束而不會(huì)中途斷開數(shù)據(jù)庫(kù)連接