1、读取操作系统设置的环境变量信息
// 读取环境变量来连接数据库
String hais_db_host = System.getenv("hais_db_host");
String hais_db_port = System.getenv("hais_db_port");
String hais_db_name = System.getenv("hais_db_name");
String hais_db_user_name = System.getenv("hais_db_user_name");
String hais_db_password = System.getenv("hais_db_password");
String url = "jdbc:mysql://" + hais_db_host + ":" + hais_db_port + "/" + hais_db_name
+ "?characterEncoding=UTF-8";
2、模拟创建连接池,通过拼接方式连接数据库
//创建连接池,包括url,passwd和user等
PooledDataSource pooledDataSource = new PooledDataSource("com.mysql.jdbc.Driver", url, hais_db_user_name,
hais_db_password);
//创建工厂事务
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("cybatis", transactionFactory, pooledDataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(SQLMapper.class);
//创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
//创建会话
public static SqlSession getSession() throws IOException {
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
//开始连接
SqlSession sqlSession = getSession();
SQLMapper sqlMapper = (SQLMapper) sqlSession.getMapper(SQLMapper.class);
List<String> results= sqlMapper.getResults();