数据库连接方式
常见错误
1.Exception in thread “main” java.lang.ClassNotFoundException: ora1cle.jdbc.driver.OracleDriver
2.Exception in thread “main” java.sql.SQLException: No suitable driver found for jdbc:orcale:thin:@localhost:1521:orcl
3.ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
4.Exception in thread “main” java.sql.SQLException: The Network Adapter could not establish the connection
5.Exception in thread “main” java.sql.SQLException: ORA-01017: invalid username/password; logon denied
6.Exception in thread “main” java.sql.SQLException: 列名无效
步骤
1.从Oracle文件下找到jdbc驱动包 ojdbc14.jar
2.项目创建及jar文件导入
1.创建JavaProject
2.项目下创建一个文件夹lib
项目上右键
new
Folder
3.将ojdbc14.jar文件复制到lib目录下
4.选中ojdbc14.jar右击—build path—add buildpath
5.注意:打开数据库监听及服务
3.数据库连接步骤eclipse中
1.导包
import java.sql.*;
2.注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
3.获取连接对象
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","a");
Connection 与特定数据库的连接(会话)在连接上下文中执行SQL语句并返回结果
//第一个参数:jdbc连接数据的url地址 jdbc:oracle:thin:@数据库服务IP:数据库端口号:数据库实例名
//第二个参数:登录数据库服务器的用户名
//第三个参数:登录数据库服务器的密码
Java与数据库可以通信 创建session窗口
4.测试是否连接成功
System.out.println(conn.getClass().getName());
连接成功:oracle.jdbc.driver.T4CConnection
5.编写sql语句
需传入的参数用占位符?代替
String sql ="select usid,uname,upwd,uimage,utype,ustate from tb_user where uname=? and upwd=?"
6.通过连接对象加载sql语句获取预编译对象
SQL语句被预编译并存储在PrepareStatement对象中
PrepareStatement pstmt = conn.prepareStatement(sql)
7.给?参数设值
pstmt.setObject(1, uname);//1表示第几个问好
pstmt.setObject(2, pwd);
8.执行查询操作
在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象
即在数据库中执行sql语句
ResultSet rs = pstmt.executeQuery()
rs.next()
next方法将光标移动到下一行 在ResultSet对象没有下一行时返回false
rs.getObject("empno")
获取empno字段的值
9.关闭所有资源
10以上保存在Map中(多Map又可以添加在list中)
添加图片—更新操作
File f = new File("E:\\Orecle_WordSpace\\1.jpg");
InputStream in = new FileInputStream(f);
byte []bt=new byte[(int)f.length()];
in.read(bt);
pstmt.setObject(3, bt);
int result=pstmt.executeUpdate();
配置文件db.propreties
-
driver_name 注册驱动 -
url -
user -
password
MyProperties
public class MyProperties extends Properties {
public static MyProperties instance = new MyProperties();
private MyProperties(){
try {
this.load(this.getClass().getClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static MyProperties getInstince(){
return instance;
}
}
帮助文档-DBHelper
1.全局变量
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
2.驱动加载static{}
static{
try {
Class.forName(MyProperties.getInstince().getProperty("driver_name"));
} catch (ClassNotFoundException e) {
System.out.println("驱动注册失败"+e.getMessage());
e.printStackTrace();
}
}
3.获取连接对象Connection getConn()
public Connection getConn(){
try {
Properties p = MyProperties.getInstince();
conn = DriverManager.getConnection(p.getProperty("url"),p);
} catch (SQLException e) {
System.out.println("获取连接对象失败:"+e.getMessage());
e.printStackTrace();
}
return conn;
}
4.设置参数? void setParams(PreparedStatement pstmt,Object…params)
public void setParams(PreparedStatement pstmt,Object...params) throws Exception{
if(params==null||params.length<=0){return ;}
for(int i=0;i<params.length;i++){
pstmt.setObject(i+1, params[i]);
}
}
5.根据结果集获取所有列名 List getColumnNames(ResultSet rs)
public List<String> getColumnNames(ResultSet rs) throws SQLException{
List<String> colunmNames = new ArrayList<String>();
ResultSetMetaData data = rs.getMetaData();
int count = data.getColumnCount();
for(int i=1;i<=count;i++){
colunmNames.add(data.getColumnName(i));
}
return colunmNames;
}
6.更新操作
1.单条sql语句更新 int update(String sql,Object…params)
public int update(String sql,Object...params) throws Exception{
int result=0;
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
setParams(pstmt, params);
result=pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("单条更新异常:"+e.getMessage());
}finally {
closeAll(conn, pstmt, null);
}
return result;
}
2.多条sql语句更新——用事务来处理
int update(List<String> sqls,List<List<Object>> params)
public int update(List<String> sqls,List<List<Object>> params) throws Exception{
int result = 0;
try {
conn=getConn();
conn.setAutoCommit(false);
for(int i=0;i<sqls.size();i++){
String sql = sqls.get(i);
List<Object> param = params.get(i);
pstmt=conn.prepareStatement(sql);
setParams(pstmt, param.toArray());
result=pstmt.executeUpdate();
if(result<=0){
conn.rollback();
return result;
}
}
conn.commit();
} catch (SQLException e) {
conn.rollback();
result=0;
e.printStackTrace();
System.out.println("多条更新异常:"+e.getMessage());
}finally {
conn.setAutoCommit(true);
closeAll(conn, pstmt, null);
}
return result;
}
7.查询操作
1.单个聚合函数查询 double getPloymer(String sql,Object…params)
select count(*) from 表名
public double getPloymer(String sql,Object...params) throws Exception{
double result=0;
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
setParams(pstmt, params);
rs=pstmt.executeQuery();
if(rs.next()){
result=rs.getDouble(1);
}
} catch (SQLException e) {
e.printStackTrace();
throw new Exception("聚合函数查询失败:"+e.getMessage());
}finally{
closeAll(conn, pstmt, rs);
}
return result;
}
2.返回一条查询结果(记录) Map<String,Object> findSingle(String sql,Object…params)
public Map<String,Object> findSingle(String sql,Object...params) throws Exception{
Map<String,Object> map=null;
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
setParams(pstmt, params);
rs = pstmt.executeQuery();
List<String> columnNames=getColumnNames(rs);
if(rs.next()){
map = new HashMap<String,Object>();
for(String name:columnNames){
Object obj = rs.getObject(name);
if(obj==null)continue;
String typeName = obj.getClass().getName();
if("oracle.sql.BLOB".equals(typeName)){
Blob blob = (BLOB)obj;
InputStream in = blob.getBinaryStream();
byte []bt=new byte[(int)blob.length()];
in.read(bt);
map.put(name, bt);
}else if("oracle.sql.CLOB".equals(typeName)){
}else{
map.put(name, rs.getObject(name));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("单条查询异常:"+e.getMessage());
}finally {
closeAll(conn, pstmt, rs);
}
return map;
}
3.返回多条查询结果(记录) List<Map<String,Object>> findMutipl(String sql,Object…params)
public List<Map<String,Object>> findMutipl(String sql,Object...params)throws Exception{
Map<String,Object> map=null;
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
try {
conn=getConn();
pstmt=conn.prepareStatement(sql);
setParams(pstmt, params);
rs = pstmt.executeQuery();
List<String> columnNames=getColumnNames(rs);
while(rs.next()){
map = new HashMap<String,Object>();
for(String name:columnNames){
Object obj = rs.getObject(name);
if(obj==null)continue;
String typeName = obj.getClass().getName();
if("oracle.sql.BLOB".equals(typeName)){
Blob blob = (BLOB)obj;
InputStream in = blob.getBinaryStream();
byte []bt=new byte[(int)blob.length()];
in.read(bt);
map.put(name, bt);
}else if("oracle.sql.CLOB".equals(typeName)){
}else{
map.put(name, rs.getObject(name));
}
}
list.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("单条查询异常:"+e.getMessage());
}finally {
closeAll(conn, pstmt, rs);
}
return list;
}
8.关闭所有资源
1.void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs)
public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
.......
}
|