首页 > 代码库 > androidj常用数据库操作JDBC Utils
androidj常用数据库操作JDBC Utils
package mypackage; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JDBCUtils { private final String USERNAME = "root"; private final String PWD = "admin"; private final String DRIVER = "com.mysql.jdbc.Driver"; private Connection connection; private java.sql.PreparedStatement preparedStatement; private ResultSet resultset; private String URL = "jdbc:mysql://localhost:3306/mydb"; public JDBCUtils() { try { Class.forName(DRIVER); System.out.println("注册驱动成功"); } catch (Exception e) { // TODO: handle exception } } // 定义获得数据库的链接 public Connection getConnection() { try { connection = DriverManager.getConnection(URL, USERNAME, PWD); } catch (Exception e) { // TODO: handle exception } return connection; } /** * * @param sql * @param params * @return * @throws SQLException */ public boolean updateByPrepareStatement(String sql, List<Object> params) throws SQLException { boolean flag = false; int result = -1;// 受影响的行数 int index = 1; preparedStatement = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { preparedStatement.setObject(index++, params.get(i)); } } result = preparedStatement.executeUpdate(); flag = result > 0 ? true : false; return flag; } /** * 查询返回单条记录 * * @param sql * @param params * @return * @throws SQLException */ public Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException { Map<String, Object> map = new HashMap<String, Object>(); int index = 1; preparedStatement = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { preparedStatement.setObject(index++, params.get(i)); } } resultset = preparedStatement.executeQuery();// 返回查询结果 ResultSetMetaData metaData = http://www.mamicode.com/resultset.getMetaData();>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。