jdbc:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
DataSource数据源:
import javax.sql.DataSource
1、属于javax.sql包,这里的x表示扩展的意思,扩展了如sql、annotation等功能;
2、DataSource就是一个接口,我们可以直接开发,只要你继承接口按照规范来
3、DataSource要是DriverMnager的替代者,通过它可以方便的搞定连接池(这个是关键)
DataSource 就是一个接口,定义了getConnection() (连接池),其余需要自己实现,比如用户名、密码,再比如连接池(核心)
1、JDBC: https://www.cnblogs.com/0328dongbin/p/9134047.html
步奏:(最原始的操作)
1.注册驱动 用来告诉JVM使用的是哪个生产厂商的驱动(现在也提供DataSource了,jdbc2.0提供javax.sql.DataSource接口)
2.获得链接,链接数据库 使用JDBC中的类,完成对MySQL数据库的链接
3.获得语句执行平台 通过连接对象获取对SQL语句的执行对象
4.执行SQL语句 使用执行对象对数据库执行SQL语句 获取执行结果
5.处理结果 处理结果集,(insert、update、delete无需处理)
6.释放资源 调用一堆 close()方法,将调用的对象弹栈
@Test
public void test() throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/goods?characterEncoding=utf-8";
String username="root";
String password="123456";
//建立数据库连接对象
Connection conn=DriverManager.getConnection(url, username, password);
//连接对象,建立语句执行对象
Statement sta=conn.createStatement();
//插入
String sqlInsert="insert into sort(sname,sdesc) value('电子设备','手机')";
int rowInsert =sta.executeUpdate(sqlInsert);
System.out.println(rowInsert);
//修改
String sqlUpdate="update sort set sname='玩具' where sid='1'";
int rowUpdate =sta.executeUpdate(sqlUpdate);
System.out.println(rowUpdate);
//查询
String sqlQuery="select * from sort";
ResultSet rs=sta.executeQuery(sqlQuery);
while(rs.next()){
System.out.println(rs.getString("sname") +"..."+ rs.getInt("sid"));
}
//删除
String sqlDel="delete from sort where sid='1'";
//释放资源
rs.close();
sta.close();
conn.close();
}
2、封装sqlite:sqlite使用
使用:
- SqliteUtil sqliteUtil = new SqliteUtil();
- Connection conn = sqliteUtile.getDatasource("D:\\abc.sq3").getConnection();
- conn.createStatement();
- .....
import org.sqlite.SQLiteDataSource;
public class SqliteUtil {
//获取数据源
public DataSource getDatasource(String sqlitefilePath) {
SQLiteDataSource dataSource = new SQLiteDataSource();
dataSource.setUrl("jdbc:sqlite:"+ sqlitefilePath);
return dataSource;
/* 对比jdbc的连接方式
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
*/
}
//创建一个空数据库
public void createDataBase(String dbPath) throws SQLException {
try (
Connection conn = getDatasource(dbPath).getConnection();
Statement stmt = conn.createStatement())
{stmt.execute("");}
}
//获取数据库里表信息
public List<String> getTables(Connection conn) throws SQLException {
List<String> tables = new ArrayList<>();
String sql = "select name from sqlite_master where type='table';";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);) {
while (rs.next()) {
tables.add(rs.getString(1));
}
}
return tables;
}
//获取数据库里表的所有字段
public List<String> getAllFields(Connection conn, String tableN) throws SQLException {
List<String> tables = new ArrayList<>();
String sql = "PRAGMA table_info(" + tableN + ");";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);) {
while (rs.next()) {
tables.add(rs.getString("name"));
}
}
return tables;
}
//获取记录
public ConnResult getRecords(String table, String sqlitefilePath) throws SQLException {
String sql = "select * from " + table;
//获取conn对象
Connection conn = getDatasource(sqlitefilePath).getConnection();
//创建执行对象
PreparedStatement ps
= conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ps.setFetchSize(Integer.MIN_VALUE-1);
//结果集
ResultSet rs = ps.executeQuery();
ConnResult cr = new ConnResult(conn, ps, rs);
return cr;
}
}
3、框架性的封装DataSource:它封装了数据库参数,连接数据库,程序中操作DataSource对象即可对数据库进行增删改查操作
Mysql datasource 的示例
//对比jdbc,注册、获取连接,DataSource是这么注册、获取连接的,其他DataSource类似,提现了java面向接口的设计思路
SQLiteDataSource dataSource = new SQLiteDataSource();
dataSource.setUrl("jdbc:sqlite:"+filePath);
Connection conn = dataSource.getConnection();
https://www.iteye.com/topic/1125144
https://blog.csdn.net/fightingXia/article/details/82555999
https://www.4spaces.org/datasource-connect-db/
https://blog.csdn.net/qq_40910541/article/details/80771607
https://blog.csdn.net/tian_qing_lei/article/details/76861689
//alibaba::tddl的数据源配置
import com.taobao.tddl.client.jdbc.TDataSource;
public TDataSource dataSource() throws TddlException {
TDataSource ds = new TDataSource();
ds.setAppName(appName);
ds.setSharding(false);
ds.init();
return ds;
}
//alibaba::Druid的数据源配置
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setDriverClassName(properties.getDriverClassName());
return dataSource;
那么,什么是数据源:
JDBC2.0 提供了javax.sql.DataSource接口,它负责建立与数据库的连接,当在应用程序中访问数据库时
不必编写连接数据库的代码,直接引用DataSource获取数据库的连接对象即可。用于获取操作数据Connection对象。
传统的JDBC访问数据库技术,每次访问数据库都需要通过数据库驱动器Driver和数据库名称以及密码等等资源建立数据库连接。
这样的连接存在两大问题:
- 1. 频繁的建立数据库连接与断开数据库,这样会消耗大量的资源和时间,降低性能。
- 2. 数据库的连接需要用户名和密码等等,这些需要一定的内存和CPU一定开销。
作为DriverManager的另一种选择,DataSource对象是获得连接的首选方法。
作为 DriverManager 工具的替代项,DataSource接口由驱动程序供应商实现。共有三种类型的实现:
- 基本实现 - 生成标准的 Connection 对象
- 连接池实现 - 它返回的Connection对象是由连接池维护的,对于基本实现和连接池实现而言,它们的事务处理要借助链接对象的setAutoCommit()、commit()、roolback()等方法完成。
- 分布式事务实现 - 生成一个 Connection 对象,该对象可用于分布式事务,大多数情况下总是参与连接池。此实现与中间层事务管理器一起使用,大多数情况下总是与连接池管理器一起使用。
4、数据库连接池:提供连接池机能的技术叫DataSource。 Javax.sql.DataSource
https://blog.csdn.net/github_26672553/article/details/78190246
https://www.cnblogs.com/nuccch/p/8120349.html
1、DataSource
2、datasource.getConnection();
数据源、读取数据的方式;
String filepath = "D:\\Tmp\\aa.sq3";
DataSource ds = sqliteDao.getDatasource(filepath);
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(ds);
String sql = "select * from Table";
Map paramMap = new HashMap(1);
//映射的方式,读取sq3内容至内存
List<People> persons = namedParameterJdbcTemplate.query(sql, paramMap, new BeanPropertyRowMapper<>(People.class));
for(People person: persons){
System.out.println(person);
}
//普通读取数据库方式,可以按照行来commit,效率更高;
Connection conn = sqliteDao.getDatasource(filepath).getConnection();
Statement stmt = conn.createStatement();
conn.setAutoCommit(false);
String sql2 = "select * from Table";
ResultSet rs = stmt.executeQuery(sql2);
while (rs.next()) {
int id = rs.getInt("id");
int id = rs.getInt("id");
}
//大于1000行时,写入效率更高
//https://blog.csdn.net/liz9411/article/details/82656554
for(){
insertRow();
}
if (cnt >= 1000) {
prest.executeBatch();
conn.commit();
cnt = 0;
}
insertRow(){
prest.set(fieldIndex,fieldValue1);
prest.set(fieldIndex++,fieldValue2);
prest.set(fieldIndex++,fieldValue3);
prest.addBatch();
};
for all values:
prepStmt.setString(1,val1);
prepStmt.setString(2,val2);
prepStmt.addBatch();
stmt.executeBatch();
conn.commit();
java多种sql查询语句
public class SqliteDao {
private String sqliteFile;
private SQLiteDataSource dataSource;
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public SqliteDao(String sqlfile){
this.sqliteFile = sqlFile;
//1、dataSource
this.dataSource = new SQLiteDataSource();
this.dataSource.setUrl("jdbc:sqlite:"+sqlFile);
//2、Connection conn = this.dataSource.getConnection(); //执行sql命令
//3、jdbcTemplate 执行sql命令
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(this.dataSource);
}
public ClsA getClsA(String table,String field, String value) {
String sql = "select * from :table where :field=:value";
Map paramMap = new HashMap(1);
paramMap.put("table", table);
paramMap.put("field", field);
paramMap.put("value", value);
ClsA ca = this.namedParameterJdbcTemplate.queryForObject(SecurityUtil.escapeSql(sql), paramMap,
new BeanPropertyRowMapper<>(ClsA.class));
return ca;
}
public ResultSet getRs(String table) throws SQLException {
String sql = "select * from " + table;
Connection conn = this.dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(SecurityUtil.escapeSql(sql), ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ps.setFetchSize(Integer.MIN_VALUE-1);
ResultSet rs = ps.executeQuery();
return rs;
}
}
mybatis:
自动生成工具
sql语句,一种写在interface里,一种写在xml里