JDBC版通讯录 ---- Java进阶篇

一.引入

1.使用mysql数据库保存数据,原来的xml做数据库的部分也保留

2.在原有项目基础上添加JDBC代码块,数据库

3.软件设计原则之开闭原则:对修改闭合,对扩展开放

 

JDBC版通讯录 ---- Java进阶篇_第1张图片

二.实现

1.建立数据库

create database contact_system   /*建库*/

use contact_system              /*使用库/进入库*/

2.建表

CREATE TABLE contact(
id VARCHAR(4) PRIMARY KEY ,
NAME VARCHAR(16) NOT NULL,
gender  VARCHAR(4)  CHECK(gender ='男' OR gender='女') ,
age INT NOT NULL,
phone VARCHAR(12) NOT NULL,
email VARCHAR(20) NOT NULL,
qq VARCHAR(16) NOT NULL 

)

3.插入测试数据

INSERT INTO contact VALUES('1','Jack','男',20,'136666666888','[email protected]','3256891478');

JDBC工具类

package cn.itcase.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * jdbc工具类
 * @author APPle
 *
 */
public class JdbcUtil {
	private static String url = null;
	private static String user = null;
	private static String password = null;
	private static String driverClass = null;
	
	/**
	 * 静态代码块中(只加载一次)
	 */
	static{
		try {
			//读取db.properties文件
			Properties props = new Properties();
			InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");// 类加载器加载文件
			
			//加载文件
			props.load(in);
			//读取信息
			url = props.getProperty("url");
			user = props.getProperty("user");
			password = props.getProperty("password");
			driverClass = props.getProperty("driverClass");
			
			
			//1.加载驱动程序
			Class.forName(driverClass);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("驱程程序注册出错");
		}
	}

	/**
	 * 抽取获取连接对象的方法
	 */
	public static Connection getConnection(){
		// 2.创建连接
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	
	/**
	 * 释放资源的方法
	 * 3.释放资源    后打开先关闭
	 */
	public static void close(Connection conn,Statement stmt){
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
	
	public static void close(Connection conn,Statement stmt,ResultSet rs){
		if(rs!=null)
			try {
				rs.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
				throw new RuntimeException(e1);
			}
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
}

contactDao接口实现类

package cn.itcase.dao_imp;

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 java.util.UUID;

import cn.itcase.dao.ContactDao;
import cn.itcase.entity.Contact;
import cn.itcase.util.JdbcUtil;

public class ContactDaoMySqlImp implements ContactDao {

	/*
	 * 添加联系人 方法
	 */
	@Override
	public void addContact(Contact contact) {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			// 创建连接
			conn = JdbcUtil.getConnection();

			// 预编译 ?占位符
			String sql = "insert into contact(id,NAME,gender,age,phone,email,qq) VALUES(?,?,?,?,?,?,?)";

			// 创建PrepareStatement
			stmt = conn.prepareStatement(sql);

			String id = UUID.randomUUID().toString().replace("-", "");
			// 设置参数
			stmt.setString(1, id);
			stmt.setString(2, contact.getName());
			stmt.setString(3, contact.getGender());
			stmt.setInt(4, contact.getAge());
			stmt.setString(5, contact.getPhone());
			stmt.setString(6, contact.getEmail());
			stmt.setString(7, contact.getQq());
			// 执行
			stmt.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException();
		} finally {
			JdbcUtil.close(conn, stmt);
		}
	}

	/*
	 * 检索输入的name值字段 是否在数据库中已存在
	 */
	@Override
	public boolean checkContact(String name) {
		Connection conn = null; // 连接对象
		PreparedStatement stmt = null;// 初始化预编译对象
		ResultSet rs = null; // 初始化结果结对象

		// 检索输入name值与是否在数据库中已存在
		try {
			conn = JdbcUtil.getConnection();// 通过工具类实现连接

			String sql = "select * from contact where name =?";

			// 创建PreparedStatement
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, name);
			// 执行
			rs = stmt.executeQuery();
			if (rs.next()) {
				return true;
			} else {
				return false;
			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);

		} finally {
			JdbcUtil.close(conn, stmt);// 调用工具类关闭资源

		}

	}

	/*根据id删除联系人*/
	@Override
	public void deleteContact(String id) {
		// 初始化
		Connection conn = null;
		PreparedStatement stmt = null;

		try {
			// 使用工具类获取连接
			conn = JdbcUtil.getConnection();
			// 预编译的删除语句
			String sql = "delete from contact where id =?";
			// 执行预编译
			stmt = conn.prepareStatement(sql);
			// 設置參數
			stmt.setString(1, id);
			// 执行
			stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.close(conn, stmt);
		}
	}

	/*查询所有联系人*/
	@Override
	public List findAll() {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			//获取连接
			conn = JdbcUtil.getConnection();
			
			String sql = "SELECT * FROM contact";
			
			//创建PreparedStatement
			stmt = conn.prepareStatement(sql);
	
			//执行
			rs = stmt.executeQuery();
			List list = new ArrayList();
			while(rs.next()){
				Contact c = new Contact();
				c.setId(rs.getString("id"));
				c.setName(rs.getString("name"));
				c.setGender(rs.getString("gender"));
				c.setAge(rs.getInt("age"));
				c.setPhone(rs.getString("phone"));
				c.setEmail(rs.getString("email"));
				c.setQq(rs.getString("qq"));
				list.add(c);
			}
			return list;
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			JdbcUtil.close(conn, stmt ,rs);
		}
	}
	/*根据id查询联系人*/
	@Override
	public Contact findByid(String id) {
		Connection conn =null;
		PreparedStatement stmt = null;
		ResultSet rs  = null;
		try {
			// 创建连接
			conn = JdbcUtil.getConnection();
			// 预编译sql
			String sql ="select * from contact where id=?";
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, id);
			//执行
			rs = stmt.executeQuery();
			Contact c= null;
			if(rs.next()){
				c = new Contact();
				c.setId(rs.getString("id"));
				c.setName(rs.getString("name"));
				c.setGender(rs.getString("gender"));
				c.setAge(rs.getInt("age"));
				c.setPhone(rs.getString("phone"));
				c.setPhone(rs.getString("email"));
				c.setQq(rs.getString("qq"));
			}
			return c;
			
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			JdbcUtil.close(conn,stmt,rs);
		}
	}
 /*修改*/
	@Override
	public void updateContact(Contact contact) {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			// 建立连接
			conn = JdbcUtil.getConnection();

			String sql = "update contact set name=?,gender=?,age=?,phone=?,email=?,qq=? where id=?";

			stmt = conn.prepareStatement(sql);
			stmt.setString(1, contact.getName());
			stmt.setString(2,contact.getGender());
			stmt.setInt(3,contact.getAge());
			stmt.setString(4,contact.getPhone());
			stmt.setString(5,contact.getEmail());
			stmt.setString(6,contact.getQq());
			stmt.setString(7,contact.getId());
			
			//执行
			stmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

db.properties文件

url=jdbc:mysql://localhost:3306/contact_system
user=root
password=root
driverClass=com.mysql.jdbc.Driver

db.properties 中出现一个红色的红线   The word is not correctly spelled  ( myeclipse  单词拼写造成的)

解决方法: 去掉Enable spell checking这个勾

JDBC版通讯录 ---- Java进阶篇_第2张图片

 

你可能感兴趣的:(JDBC版通讯录 ---- Java进阶篇)