首页 > 分享 > JDBC连接 数据库

JDBC连接 数据库

Java Database Connectivity

概念

JAVA数据库连接技术

主要功能

1.与数据库建立连接、执行SQL语句、处理结果

相关对象功能

DriverManager:

管理JDBC驱动

Connection:

负责数据库连接并传送数据任务

Statement:

负责执行SQL语句

ResultSet:

负责保存结果(结果集)

操作步骤

加载JDBC驱动

Class.forName(........);

建立与数据库连接

Connection con=DriverManager.getConnection(URL,数据库用户名,密码); "jdbc:mysql://localhost:3306/world?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT","xxxx","xxxx"

发送SQL语句得到结果集

Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(String sql); ​

释放资源

rs.close(); stmt.close();   con.close(); Statement常用方法

ResultSet executeQuery(String sql)//执行sql查询并获得结果集 int executeUpdate(String sql)//可以执行插入、删除、更新等操作,返回的是执行操作影响的行数 boolean execute(String sql)//执行任意sql语句,获得一个布尔值,表示是否返回ResultSet void  close()//关闭 ResultSet

boolean next()//将游标从当前位置向下移动一行 boolean previous()//游标从当前位置向上移动一行 void close()//关闭ResultSet 对象 int getInt(int colIndex)//以int形式获取结果集当前行指定列号值 int getInt(String colLabel)//以int形式获取结果集当前行指定列名值 float getFloat(int colIndex)//以float形式获取结果集当前行指定列号值 float getFloat(String colLabel)//以float形式获取结果集当前行指定列名值 String getString(int colIndex)//以String 形式获取结果集当前行指定列号值 String getString(String colLabel)//以String形式获取结果集当前行指定列名值 PreparedStatement

优点

1.提高代码的可读性与可维护性

2.提高sql语句的执行性能

3.提高了安全性

举例

public static void main(String[] args) { Connection conn = null; PreparedStatement pstmt = null; conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/epet", "epetadmin", "0000"); // 3、更新狗狗信息到数据库 String sql="update dog set health=?,love=? where id=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, 80); pstmt.setInt(2, 15); pstmt.setInt(3, 1); pstmt.executeUpdate(); pstmt.setInt(1, 90); pstmt.setInt(2, 10); pstmt.setInt(3, 2); pstmt.executeUpdate(); logger.info("成功更新狗狗信息!"); } catch (SQLException e) { logger.error(e); } finally { // 4、关闭Statement和数据库连接 try { if (null != pstmt) { pstmt.close(); } if (null != conn) { conn.close(); } } catch (SQLException e) { logger.error(e); } } }

DAO模式(Data Access Object(数据存取对象) )

数据持久化的概念

将程序中的数据在瞬时状态和持久状态间转换的机制即为数据的持久化

JDBC封装

1.提高可读性

2.利于后期维护与修改

3.增强代码的复用性

4.降低代码之间的耦合

5.隔离业务逻辑代码与数据库访问代码

6.隔离不同的数据库的实现

JDBC封装步骤

定义实体类

public class Pet{ private int id;// 宠物id private int masterId;// 主人id private String name;// 昵称 …… public int getId(){ return id; } public void setId(int id){ this.id = id; } …… } ​

对实体类的所有操作抽取成接口

public interface PetDao{    int save(Pet pet);    int del(Pet pet);    int update(Pet pet);    Pet getByName(String name);    List<Pet> findByName(String name);    List<Pet> findByType(String type);} ​

创建BaseDAO(待改良)

public class BaseDao{ private  String driver = " com.mysql.jdbc.Driver";        private   String url = "jdbc:mysql://localhost:3306/epet";               … …        public  Connection getConnection() {   … …              Class.forName(driver);       conn = DriverManager.getConnection(url, user, password);       … …       return conn;       }      public void closeAll(Connection conn, Statement stmt,ResultSet rs) {       if(rs != null) rs.close();   if(stmt != null)stmt.close();   … … }    public int exceuteUpdate (String preparedSql, Object[] param) {         … …         conn =  getConnection();         try { pstmt = conn.prepareStatement(preparedSql); if (param != null) {        for (int i = 0; i < param.length; i++) {                               //为预编译sql设置参数 pstmt.setObject(i + 1, param[i]);       } } num = pstmt.executeUpdate();         } … … } ​ } ​

实现类实现接口并继承数据库工具类

public class PetDaoMySQLImpl2 extends BaseDao implements PetDao{    //更新宠物状态 public int update(Pet pet) { String sql="update pet set status=0 where id=?"; Object[] param={pet.getId()}; int result=this.exceuteUpdate(sql, param); return result; } //省略实现PetDao的其他方法 } ​ ​ 使用Properties类

添加.properties文件

调用properties方法

String getProperty(String key)//用指定的键在此属性列表中搜索属性。通过参数key得到其所对应的值 Object setProperty(String key,String value)//调用Hashtable的方法put。通过调用基类的put()方法来设置键-值对 void load(InputStream inStream)//从输入流中读取属性列表 (键和元素对)。通过对指定文件进行装载获取该文件中所有键-值对 void clear()//清除所装载的键-值对,该方法由基类Hashtable提供 改良后的BaseDAO

public class BaseDao { //省略变量定义代码…… static{ init();} public static void init(){ Properties params=new Properties(); String configFile = "database.properties"; InputStream is=BaseDao.class.getClassLoader()                               .getResourceAsStream(configFile); try { params.load(is); } catch (IOException e) {//….} driver=params.getProperty("driver"); url=params.getProperty("url"); user=params.getProperty("user"); password=params.getProperty("password"); } //省略其他方法代码……} ​ 使用实体类传递数据注意点

属性一般使用private修饰

提供public修饰的getter/setter方法

实体类提供无参构造方法,根据业务提供有参构造

实现java.io.Serializable接口,支持序列化机制

如果不实现这个接口,在某些数据持久框架下进行数据持久化会出现问题。hibernate就是这样的

代码实现 

数据库模型

第一编写实体类

package kgc.pojo;

public class Grade {

private int GradeId;

private String gradeName;

@Override

public boolean equals(Object obj) {

return super.equals(obj);

}

@Override

public int hashCode() {

return super.hashCode();

}

public int getGradeId() {

return GradeId;

}

public void setGradeId(int gradeId) {

GradeId = gradeId;

}

public String getGradeName() {

return gradeName;

}

public void setGradeName(String gradeName) {

this.gradeName = gradeName;

}

public Grade(int gradeId, String gradeName) {

super();

GradeId = gradeId;

this.gradeName = gradeName;

}

public Grade() {

super();

}

@Override

public String toString() {

return "Grade [gradeId=" + this.GradeId + ", gradeName=" + this.gradeName + "]";

}

}

第二 编写  接口

开闭接口

package kgc.dao.inner;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

public interface IBaseDao {

Connection getOpen();

void getClose(Connection con,PreparedStatement ps,ResultSet rs);

}

增删改查接口

package kgc.dao.inner;

import java.util.List;

import kgc.pojo.Grade;

public interface IGradeDao {

boolean add(Grade g);

boolean delete(Grade g);

boolean renewal(Grade g);

Grade selectOne(int id);

List<Grade> selectAll();

}

第三 编写实现类

package kgc.dao;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import kgc.dao.inner.IBaseDao;

public class BaseDao implements IBaseDao {

Connection connection = null;

@Override

public Connection getOpen() {

try {

Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/kj15?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";

connection = DriverManager.getConnection(url, "root", "123qwe");

} catch (Exception e) {

}

if (connection == null) {

throw new NullPointerException();

}

return this.connection;

}

@Override

public void getClose(Connection con, PreparedStatement ps, ResultSet rs) {

if (rs != null) {

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (con != null) {

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

package kgc.dao;

import java.awt.TexturePaint;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import kgc.dao.inner.IGradeDao;

import kgc.pojo.Grade;

@SuppressWarnings("all")

public class GradeDao extends BaseDao implements IGradeDao {

@Override

public boolean add(Grade g) {

Connection con = getOpen();

PreparedStatement ps=null;

try {

ps = con.prepareStatement("insert into Grade(gradeName) values(?)");

ps.setString(1, g.getGradeName());

int ee = ps.executeUpdate();

if (ee>0) {

return true;

}else {

return false;

}

} catch (SQLException e) {

e.printStackTrace();

}

getClose(con, ps, null);

return false;

}

@Override

public boolean delete(Grade g) {

Connection con = getOpen();

PreparedStatement ps=null;

try {

ps = con.prepareStatement("delete from grade where id=? ");

ps.setInt(1, g.getGradeId());

int ee = ps.executeUpdate();

if (ee>0) {

return true;

}else {

return false;

}

} catch (SQLException e) {

e.printStackTrace();

}

getClose(con, ps, null);

return false;

}

@Override

public boolean renewal(Grade g) {

Connection con = getOpen();

PreparedStatement ps=null;

try {

ps = con.prepareStatement("update grade set gradename=? where gradeid=? ");

ps.setString(1, g.getGradeName());

ps.setInt(2, g.getGradeId());

int ee = ps.executeUpdate();

if (ee>0) {

return true;

}else {

return false;

}

} catch (SQLException e) {

e.printStackTrace();

}

getClose(con, ps, null);

return false;

}

@Override

public Grade selectOne(int id) {

Connection con = getOpen();

PreparedStatement ps=null;

ResultSet ey=null;

try {

ps = con.prepareStatement("select * from grade where gradeid=? ");

ps.setInt(1, id);

ey = ps.executeQuery();

while (ey.next()) {

int int1 = ey.getInt(1);

String string = ey.getString(2);

Grade grade = new Grade(int1,string);

return grade;

}

} catch (SQLException e) {

e.printStackTrace();

}

getClose(con, ps, ey);

return null;

}

@Override

public List<Grade> selectAll() {

Connection con = getOpen();

PreparedStatement ps=null;

ResultSet rs=null;

ArrayList<Grade> List = new ArrayList<>();

try {

ps = con.prepareStatement("select * from grade ");

rs = ps.executeQuery();

while (rs.next()) {

int int1 = rs.getInt(1);

String string = rs.getString(2);

Grade grade = new Grade(int1,string);

List.add(grade);

}

return List;

} catch (SQLException e) {

e.printStackTrace();

}

getClose(con, null, null);

return List;

}

}

第5 测试

package kgc.demo;

import java.util.List;

import kgc.dao.GradeDao;

import kgc.pojo.Grade;

public class JdbcDemo {

public static void main(String[] args) {

Grade ge = new Grade(1, "我入土阶段");

boolean add = new GradeDao().add(ge);

System.out.println(add);

GradeDao gd = new GradeDao();

List<Grade> selectAll = gd.selectAll();

Grade grade = selectAll.get(selectAll.size() - 1);

boolean delete = gd.delete(grade);

System.out.println(delete);

GradeDao gd1 = new GradeDao();

List<Grade> selectAll1 = gd.selectAll();

Grade grade1 = selectAll1.get(selectAll.size() - 1);

grade1.setGradeName("升天阶段");

boolean renewal = gd1.renewal(grade1);

System.out.println(renewal);

GradeDao gd2 = new GradeDao();

Grade selectOne = gd2.selectOne(1);

System.out.println(selectOne);

GradeDao gd3 = new GradeDao();

List<Grade> selectAll11 = gd3.selectAll();

for (Grade grade11 : selectAll11) {

System.out.println(grade11);

}

}

}

JDBC成功连接数据库啦!!!

以上方法还能改进 后续会补!!!!!!

相关知识

Java实现Mysql的jdbc连接例子
JDBC实战案例
使用JDBC实现简单的宠物系统(增删改查)
useSSL=false 连接配置详解
jsp宠物医院信息管理系统17455(程序+源码+数据库+调试部署+开发环境)
C#连接数据库模块rar
jsp宠物医院管理系统xc416(程序+源码+数据库+调试部署+开发环境)
jsp宠物医院管理系统58rr2(程序+源码+数据库+调试部署+开发环境)
jsp宠物医院管理系统4z632(程序+源码+数据库+调试部署+开发环境)
jsp宠物狗领养网站57146(程序+源码+数据库+调试部署+开发环境)

网址: JDBC连接 数据库 https://m.mcbbbk.com/newsview460288.html

所属分类:萌宠日常
上一篇: 【攻略】一天赚3600万师门贡献
下一篇: 甲醛知识全面总结,家装知识贮备