1.连接数据库
import java.sql.*;
import java.util.*;
public class DbUtil {
static String driverClass = "oracle.jdbc.driver.OracleDriver"; //oracle的驱动
static String url = "jdbc:oracle:thin:@localhost:1521:";
static String user = "testuser"; //testuser是数据库的用户名
static String password = "111111"; //用户登录密码
public static Connection getConn() { //为了方便下面的讲解,这里专门建立了一个用于数据库连接的一个方法
Connection conn = null;
try {
//首先加载驱动
Class.forName(driverClass);
//驱动成功后进行连接
conn= DriverManager.getConnection(url, user, password);
System.out.println("连接成功");
} catch (Exception e) {
System.err.println("连接失败:"+e.getMessage());
}
return conn; //返回一个连接
}
}
2.测试连接
3.新建数据表U
包含ID,NAME,AGE,并添加测试数据
4.封装查询方法
/**
* @param connection 数据库连接对象
* @param sql 语句
* @param param 查询参数
* @return Object对象
*
*/
public static Object selectEq(Connection connection, String sql, Map param,Map resultMap) {
Statement st;
ResultSet rs;
StringBuilder stringBuilderSql = new StringBuilder(sql);
if (param != null && !param.isEmpty()) {
stringBuilderSql.append(" where ");
Object[] field = param.keySet().toArray();
for (int i = 0; i < field.length; i++) {
stringBuilderSql.append(field[i].toString()).append("=").append(param.get(field[i]));
if (i > 0) {
stringBuilderSql.append(" and ").append(field[i]).append("=").append(param.get(field[i]));
}
}
}
try {
//1、创建statement类对象,用来执行SQL语句
st = connection.createStatement();
//2、创建sql查询语句
rs = st.executeQuery(stringBuilderSql.toString());
//3、执行sql语句并且换回一个查询的结果集
while (rs.next()) { //循环遍历结果集
Object[] objects = resultMap.keySet().toArray();
for (int i = 0; i < objects.length; i++) {
resultMap.put(objects[i],rs.getString(objects[i].toString()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
由于程序非web项目所以本人没有写关闭连接,若集成在web项目中需要在返回结果后关闭连接
5.测试查询
import db.DbUtil;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
public class Run {
public static void main(String[] args) {
Connection connection = DbUtil.getConn();
Map<String,String>param = new HashMap<>();
Map<String,String>resultMap = new HashMap<>();//返回结果
param.put("age","20");//查询条件
resultMap.put("id","");
resultMap.put("name","");
resultMap.put("age","");
System.out.println(DbUtil.selectEq(connection,"select * from u",param,resultMap));
}
}
本代码旨在演示jdbc用法