JDBC查询插入数据库
Posted gikin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC查询插入数据库相关的知识,希望对你有一定的参考价值。
连接数据库操作:
[1]连接数据库的基本数据:
public class DB_Util public static String DRIVERS = ""; public static String URL = ""; public static String USER = ""; public static String PASSWORD = ""; static Properties prop = new Properties(); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); try prop.load(in); DRIVERS = prop.getProperty("driver"); URL = prop.getProperty("url"); USER = prop.getProperty("user"); PASSWORD = prop.getProperty("password"); catch (IOException e) e.printStackTrace();
需求的配置表:
#connection #mysql driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test user=Gikin_db password=tiger #oracle #driver=oracle.jdbc.driver.OracleDriver #url=jdbc:oracle:thin:@//loaclhost:1521/orcl #user=SCOTT #password=tiger
【2】连接数据库:
public static Connection openDB() Connection con = null; try Class.forName(DB_Util.DRIVERS); con = DriverManager.getConnection(DB_Util.URL, DB_Util.USER, DB_Util.PASSWORD); catch (Exception e) e.printStackTrace(); return con; public static void closeDB(Connection con, Statement stmt, ResultSet rs) try if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); catch (SQLException e) e.printStackTrace(); finally rs = null; stmt = null; con = null;
【3】断开数据库:
public static void closeDB(Connection con, Statement stmt, ResultSet rs) try if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); catch (SQLException e) e.printStackTrace(); finally rs = null; stmt = null; con = null; public static void closeDB(Connection con, Statement stmt) try if (stmt != null) stmt.close(); if (con != null) con.close(); catch (SQLException e) e.printStackTrace(); finally stmt = null; con = null;
Select查询:
public static void main(String[] args) //构造查询条件sql语句 String sql = "where deptno = ?"; //Object[]中存储的是要查询的条件,同时反射获得实体 List<?> list = SELECT.getROW(sql,new Object[] 20, EMP.class); for (Object object : list) System.out.println(object);
连接数据库查询:
public static String creatSetter(String colName) //利用传入的属性名拼接set方法名 String setMethod = "set" + colName.substring(0, 1) + colName.substring(1).toLowerCase(); return setMethod; public static List<?> getROW(String sql, Object[] obj, Class<?> clazz) List<Object> list = new ArrayList<Object>(); //通过实体获得类名,同时也是表名 String clazzName = clazz.getSimpleName(); //拼接sql语句 String selectSQL = "select * from " + clazzName + " " + sql; Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try //连接数据库 con = DBHelp.openDB(); //将sql存入PreparedStatement对象准备发送到数据库 ps = con.prepareStatement(selectSQL); //绑定Object[]中的条件到ps中的sql上的?占位符 for (int i = 0; i < obj.length; i++) ps.setObject(i + 1, obj[i]); //执行sql语句,返回一个结果集 rs = ps.executeQuery(); while (rs.next()) //获得实例 Object instance = clazz.newInstance(); //获得结果集中的每列的数量,类型和属性 ResultSetMetaData metaData = rs.getMetaData(); for (int i = 0; i < metaData.getColumnCount(); i++) //获得列名即字段名 String colName = metaData.getColumnName(i + 1); //获得结果集中每列对应的值 Object colValue = rs.getObject(i + 1); //获得类中的属性 Field field = clazz.getDeclaredField(colName.toLowerCase()); //获得类属性对应的set方法 Method method = clazz.getDeclaredMethod(creatSetter(colName), field.getType()); //Mysql中的数据类型需要转换才能赋入对象 if (colValue instanceof Number) if (field.getType().getName().equals("int") || field.getType().getName().equals("java.lang.Integer")) method.invoke(instance, ((Number) colValue).intValue()); else if (field.getType().getName().equals("float") || field.getType().getName().equals("java.lang.Float")) method.invoke(instance, ((Number) colValue).floatValue()); else if (field.getType().getName().equals("double") || field.getType().getName().equals("java.lang.Double")) method.invoke(instance, ((Number) colValue).doubleValue()); else if (colValue == null) method.invoke(instance, 0.0); else method.invoke(instance, colValue); list.add(instance); catch (Exception e) e.printStackTrace(); finally DBHelp.closeDB(con, ps, rs); return list;
Insert插入:
//构造插入的对象 EMP emp = new EMP(1111, "cai111", "singer", 7788,new Date(), 5600, 10.0, 10); int isSuccess = INSERT.insert(emp); System.out.println( isSuccess==1 ? "添加成功!" : "添加失败!");
连接数据库操作:
public static int insert(Object obj) int isSuccess = 0; Connection conn = DBHelp.openDB(); PreparedStatement ps = null; //拼接sql语句,属性使用"?"占位符等待绑定 String SQL = "insert into " + obj.getClass().getSimpleName() + " values(?,?,?,?,?,?,?,?)"; // System.out.println(SQL); try ps = conn.prepareStatement(SQL); Field[] fields = obj.getClass().getDeclaredFields(); //依次绑定属性到占位符上 for (int i = 0; i < fields.length; i++) //java的Date需要转换为sql的Date才能添加到数据库 if (setField(obj, fields[i]) instanceof Date) Date date = (Date) setField(obj, fields[i]); //所有的数据类型均继承自Object,所以直接使用Object避免类型不匹配异常 ps.setObject(i+1,new java.sql.Date(date.getTime())); else ps.setObject(i+1,setField(obj, fields[i])); //执行sql语句,返回一个int表示是否操作成功 isSuccess = ps.executeUpdate(); //提交 conn.commit(); catch (SQLException e) e.printStackTrace(); finally DBHelp.closeDB(conn, ps); return isSuccess; public static Object setField(Object obj,Field field) String name = field.getName(); String methodName = "get" + name.substring(0,1).toUpperCase() + name.substring(1,name.length()); Object setField = null; try Method method = obj.getClass().getMethod(methodName); setField = method.invoke(obj); catch (NoSuchMethodException e) e.printStackTrace(); catch (SecurityException e) e.printStackTrace(); catch (IllegalAccessException e) e.printStackTrace(); catch (IllegalArgumentException e) e.printStackTrace(); catch (InvocationTargetException e) e.printStackTrace(); return setField;
以上是关于JDBC查询插入数据库的主要内容,如果未能解决你的问题,请参考以下文章
编写一个java程序,通过jdbc访问数据库实现对数据库的插入,删除,修改和查询操作
编写一个java程序,通过jdbc访问数据库实现对数据库的插入,删除,修改和查询操作