Java Dao操作数据库实例
package com.zykj.hbase.back.dao;
import com.zykj.hbase.back.utils.JdbcUtil;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* description
*
* @author ${user}
* @Time 2019-04-08
*/
public class DaoImp implements Dao {
// JDBC driver name and database URL
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// static final String DB_URL = "jdbc:mysql://10.129.18.17:3306/hfqx?useUnicode=true&characterEncoding=utf-8";
//
// // Database credentials
// static final String USER = "root";
// static final String PASS = "123";
static final String DB_URL = JdbcUtil.getJDBCURL();
static final String JDBC_DRIVER = JdbcUtil.getJDBCDriver();
static final String USER = JdbcUtil.getUserName();
static final String PASS = JdbcUtil.getPassWord();
Connection conn = null;
Statement stmt = null;
{
try
{
// Class.forName("com.mysql.jdbc.Driver");
System.out.println(JDBC_DRIVER + " " + DB_URL + " "
+ USER + " " + PASS);
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
} catch(ClassNotFoundException e) {
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
}
}
@Override
public ResultSet executesql(String sql) {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
@Override
public List<String> queryForList(String sql) {
ResultSet resultSet = executesql(sql);
List<String> resultlist = new ArrayList<String>();
try {
while(resultSet.next()) {
String stationid1 = resultSet.getString(1);
resultlist.add(stationid1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return resultlist;
}
@Test
public void TestSql() {
DaoImp daoImp = new DaoImp();
String sql = "SELECT Station_Id_C FROM STATION_META_TAB";
List<String> resultlist = daoImp.queryForList(sql);
System.out.println(resultlist.size());
}
}