一、JDBC
1、JDBC:java DataBase Connectivity
2、JDBC 的作用:
(1)、建立与数据库之间的访问连接
(2)、将sql语句发送到数据库执行
(3)、对数据库返回的结果进行处理
3、JDBC访问数据库过程
(1)、加载驱动 driver
(2)、获得连接 DriverManager.getconnection
(3)、创建statement对象,执行sql
连接.createStatement();
String sql =”sql表查询语句”
对象.executeQuery(sql);
(4)、遍历Resultset
(5)、关闭流释放资源
注意!!!
链接数据库前,声明四个变量—-四要素;、
driver url userName password
/*
SQLyog 企业版 - MySQL GUI v8.14
MySQL - 5.5.32-log : Database - kgcnews
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`kgcnews` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;
USE `kgcnews`;
/*Table structure for table `news_category` */
DROP TABLE IF EXISTS `news_category`;
CREATE TABLE `news_category` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`createDate` DATETIME DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='新闻分类表';
/*Data for the table `news_category` */
INSERT INTO `news_category`(`id`,`name`,`createDate`) VALUES (1,'国内','2016-09-16 14:41:24'),(2,'国际','2016-09-16 14:42:58'),(3,'娱乐','2016-09-16 14:42:58'),(4,'军事','2016-09-16 14:42:58'),(5,'财经','2016-09-16 14:42:58'),(6,'天气','2016-09-16 14:42:58');
/*Table structure for table `news_comment` */
DROP TABLE IF EXISTS `news_comment`;
CREATE TABLE `news_comment` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT COMMENT 'id',
`newsId` BIGINT(10) DEFAULT NULL COMMENT '评论新闻id',
`content` VARCHAR(2000) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '评论内容',
`author` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '评论者',
`ip` VARCHAR(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '评论ip',
`createDate` DATETIME DEFAULT NULL COMMENT '发表时间',
PRIMARY KEY (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='新闻评论表';
/*Data for the table `news_comment` */
/*Table structure for table `news_detail` */
DROP TABLE IF EXISTS `news_detail`;
CREATE TABLE `news_detail` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT COMMENT 'id',
`categoryId` BIGINT(10) DEFAULT NULL COMMENT '新闻类别id',
`title` VARCHAR(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '新闻标题',
`summary` VARCHAR(200) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '新闻摘要',
`content` TEXT COLLATE utf8_unicode_ci COMMENT '新闻内容',
`picPath` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '新闻图片路径',
`author` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '发表者',
`createDate` DATETIME DEFAULT NULL COMMENT '创建时间',
`modifyDate` DATETIME DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='新闻明细表';
/*Data for the table `news_detail` */
INSERT INTO `news_detail`(`id`,`categoryId`,`title`,`summary`,`content`,`picPath`,`author`,`createDate`,`modifyDate`) VALUES (1,1,'Java Web开课啦','Java Web课程重磅开课,学员福利','璇女神主讲,课工场倾力出品,Java Web课程开课了,等靠谱的你来报名!','','admin','2016-05-16 14:43:53','2015-05-16 14:43:53'),(2,1,' 520课工场Java狂欢节','课工场准备了一大波福利:Java大赛、折扣课程,免费线下福利……你准备好了吗?','在这个五月,课工场Java学员突破100万人。为感谢所有学员的支持,我们特将5月20日定为【课工场Java狂欢节】。课工场准备了一大波福利:Java大赛、折扣课程,免费线下福利……你准备好了吗?',NULL,'admin','2016-05-16 14:43:53','2016-05-16 14:43:53');
/*Table structure for table `news_user` */
DROP TABLE IF EXISTS `news_user`;
CREATE TABLE `news_user` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`userName` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户名',
`password` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '密码',
`email` VARCHAR(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'email',
`userType` INT(5) DEFAULT NULL COMMENT '用户类型 0:管理员 1:普通用户',
PRIMARY KEY (`id`)
) ENGINE=MYISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='用户表';
/*Data for the table `news_user` */
INSERT INTO `news_user`(`id`,`userName`,`password`,`email`,`userType`) VALUES (1,'admin','admin','admin@kgc.cn',0),(2,'user','user','user@kgc.cn',1),(3,'test','test','test@kgc.cn',1);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
`news_user`
package cn.bdqn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
public class JDBCTest1 {
//链接数据库前,声明四个变量---四要素
String driver="com.mysql.jdbc.Driver";//驱动名称
String url="jdbc:mysql://127.0.0.1:3306/kgcnews";//数据库地址
String userName = "root";//用户名
String password="123456";//密码(mysql自己的密码)
/*
* 链接数据库,获取detail,查询新闻内容列表
*/
public void getNewsDetailList(){
Connection connection=null;
Statement stat=null;
ResultSet rs=null;
try {
//1.加载驱动(java反射实现)
Class.forName(driver);
//2.DriverManager类来获取connection链接
connection=DriverManager.getConnection(url, userName, password);
//3.创建Statement对象,执行SQL语句
stat=connection.createStatement();
String sql ="select * from news_detail";
//执行sql后保存结果
rs=stat.executeQuery(sql);
//4.遍历Resultset 获得返回结果
while(rs.next()){
int id=rs.getInt("id");
String title=rs.getString("title");
Timestamp createDate=rs.getTimestamp("createDate");
System.out.println(id+"--"+title+"--"+createDate);
}
//5.finally中关闭流,释放资源
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(rs!=null){
rs.close();
}
if(stat!=null){
stat.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JDBCTest1 jt1=new JDBCTest1();
jt1.getNewsDetailList();
}
}
二、单例模式
1、非单例模式
提供私有的构造方法和公有静态返回值获得实例方法
public class NoSingleton{
//私有构造
private NoSingleton(){
}
public static Nosingleton getInstance(){
return new NoSingleton;
}
}
测试
public static void main (String[] args){
//非单例两次得到的值不同
//由于构造方法被私有化,所有不能直接new出来,只能.方法
// 非单例模式测试
//不能直接创建,因为构造方法被私有化,输出两值不一样
//NoSingleton ns=new NoSingleton();
//如何创建对象呢?
NoSingleton nsl1=NoSingleton.getInstance;
syso.out.print(nsl1);
NoSingleton nsl2=NoSingleton.getInstance;
syso.out.print(nsl2);
}
2、单例模式
单例模式分为3种:饿汉式 ,懒汉式和双检锁模式
/
单例模式 在系统运行期间内 有且只有一个实例
1、构造方法私有化
2、提供静态的公有方法,返回实例
*/
(1)、饿汉式
饿汉式:
在系统加载类的时候就创建好这个实例,只创建一次static保证只创建一次。
以空间换时间 ```java public class EhanShi{ //第一种static EhanShi sEhan= new EhanShi(); //第二种 静态代码块 //在获得实例前先定义变量 static EhanShi es = null; static {es= new EhanShi();
} private EhanShi(){
} public static EhanShi getInstance(){
return es
}
}
测试 public static void main (String[] args){ EhanShi es1=EhanShi.getInstance(); syso.out.print(es1); EhanShi es2=EhanShi.getInstance(); syso.out.print(es2); }
<a name="MYcUh"></a>
### (2)、懒汉式
/*<br /> * 懒汉式 <br /> * 在使用的时候才创建,只创建一次<br /> * 用时间换空间 使用创建需要耗时,空间节省<br /> * 请求一次上一次锁
- 由于在使用时候创建,在方法中要判断
*/
```java
public class LanHanShi{
//私有构造
static LanHanShi lhs=null;
private LanHanShi(){
}
//静态返回值方法 一面出现不同值,可以加个锁限制
public static synchronized LanHanShi getInstance(){
if(lhs==null){
lhs=new LanHanShi();
}
return lhs;
}
}
测试---用线程
public static void main (String[] args){
//懒汉式用之前的 测试方法,出现的值相同,但是在线程测试中有几率出现不同值,所以优化一下,加个锁
//线程测试
Thread th1= new Thread(new Runnable(){
Thread.sleep(1);//要处理异常,目的是为了两次进入不并发
public void run(){
LanHanShi lhs1=LanHanShi.getInstance();
syso.out.print(lhs1);
}
});
Thread th2= new Thread(new Runnable(){
public void run(){
LanHanShi lhs2=LanHanShi.getInstance();
syso.out.print(lhs2);
}
});
th1.start();
th2.start();
}
(3)、双重检锁
/
双检锁—双重检查锁
懒汉升级版—效率更高
只有第一次上锁,之后再请求不许要上
volatile 变量加上后单例始终不会失效
1.内存可见性
2.禁止指令重排序
/
public class DoubleLock{
//
static volatile DoubleLock dl=null;
private DoubleLock(){
}
public static DoublieLock getInstance(){
//第一重
if(dl==null){
//进入第二重
synchronized(DoubleLock.class){
if(dl==null){
dl=new DoubleLock();
}
}
}
return dl;
}
}
测试--线程
public static void main (String[] args){
//懒汉式用之前的 测试方法,出现的值相同,但是在线程测试中有几率出现不同值,所以优化一下,加个锁
//线程测试
Thread th1= new Thread(new Runnable(){
Thread.sleep(1);//要处理异常,目的是为了两次进入不并发
public void run(){
LanHanShi lhs1=LanHanShi.getInstance();
syso.out.print(lhs1);
}
});
Thread th2= new Thread(new Runnable(){
public void run(){
LanHanShi lhs2=LanHanShi.getInstance();
syso.out.print(lhs2);
}
});
th1.start();
th2.start();
}
3、单例模式的优缺点?
单例模式的优缺点
(优点)
单例类只有一个实例,节省了内存资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能;
单例模式可以在系统设置全局的访问点,优化和共享数据,例如前面说的Web应用的页面计数器就可以用单例模式实现计数值的保存。
(缺点)
单例模式一般没有接口,扩展的话除了修改代码基本上没有其他途径。
4、懒汉和饿汉的区别?
(1)、饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变。懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的。
(2)、从实现方式来讲他们最大的区别就是懒汉式是延时加载,他是在需要的时候才创建对象,而饿汉式在虚拟机启动的时候就会创建,;类加载较慢,但获取对象速度快,所以看成“空间换时间”,类的加载速度较快,但运行时间慢,所以看成“时间换空间”
三、使用配置文件访问数据库
原因:优势在于,可以一次性编写,随时调用,并且一旦数据库发生变化,只要随时修改配置文件即可,无需修改源代码;
dataBase文件
#mysql数据库驱动
driver=com.mysql.jdbc.Driver
#数据库URL
url=jdbc:mysql://127.0.0.1:3306/kgcnews
#用户名
userName=root
#密码
password=123456
configManager类
package cn.bdqn.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/*
* 读取数据库的配置文件
* 只读取一次 采用单例模式
*/
public class ConfigManager {
//单例模式 启动的时候加载好--饿汉
private static ConfigManager cofigManager= new ConfigManager();
//声明properties对象
private Properties properties;
private ConfigManager(){
//数据库配置文件初始化
String configFile="dataBase.properties";
properties=new Properties();
//读取文件configFile返回文件流,通过ConfigManager获得
//getClassLoader对象读取指定的 文件信息,返回InputStream
InputStream is=ConfigManager.class.getClassLoader()
.getResourceAsStream(configFile);
try {
//加载文件流 load()读取配置文件
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static ConfigManager getInstance(){
return cofigManager;
}
//通过key获取value值
public String getValue(String key){
return properties.getProperty(key);
}
}
JDBCTest测试类
package cn.bdqn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import cn.bdqn.util.ConfigManager;
public class JDBCTest1 {
//链接数据库前,声明四个变量---四要素
String driver=ConfigManager.getInstance().getValue("driver");//驱动名称
String url=ConfigManager.getInstance().getValue("url");//数据库地址
String userName = ConfigManager.getInstance().getValue("userName");//用户名
String password=ConfigManager.getInstance().getValue("password");//密码(mysql自己的密码)
/*
* 链接数据库,获取detail,查询新闻内容列表
*/
public void getNewsDetailList(){
Connection connection=null;
Statement stat=null;
ResultSet rs=null;
try {
//1.加载驱动(java反射实现)
Class.forName(driver);
//2.DriverManager类来获取connection链接
connection=DriverManager.getConnection(url, userName, password);
//3.创建Statement对象,执行SQL语句
stat=connection.createStatement();
String sql ="select * from news_detail";
//执行sql后保存结果
rs=stat.executeQuery(sql);
//4.遍历Resultset 获得返回结果
while(rs.next()){
int id=rs.getInt("id");
String title=rs.getString("title");
Timestamp createDate=rs.getTimestamp("createDate");
System.out.println(id+"--"+title+"--"+createDate);
}
//5.finally中关闭流,释放资源
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(rs!=null){
rs.close();
}
if(stat!=null){
stat.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JDBCTest1 jt1=new JDBCTest1();
jt1.getNewsDetailList();
}
}
四、优化操作
查询新闻列表;全查news_detail所有数据
1、dao包—-BaseDao
2、dao包—-NewsDetailDao接口
3、pojo包—-NewsDetail实体类
4、impl包—-NewsDetailDaoImpl接口实现类
5、dao包—-Test测试类
BaseDao:
public class BaseDao{
//父类,基础Dao类存储等公共操作
String driver = ConfigManager.getInstance().getValue("driver");
String url=ConfigManager.getInstance().getValue("url");//数据库地址
String userName = ConfigManager.getInstance().getValue("userName");//用户名
String password=ConfigManager.getInstance().getValue("password");//密码(mysql自己的密码)
protected Connection connection = null;
protected PreparedStatement pstat = null;
protected ResultSet rs = null;
//获得数据库连接方法
public Connection getConnection(){
try {
Class.forName(driver);
connection=DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
//统一释放资源方法
public void close(){
try {
if(rs!=null){
rs.close();
}
if(pstat!=null){
pstat.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
接口实现类:
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.bdqn.dao.BaseDao;
import cn.bdqn.dao.NewsDetailDao;
import cn.bdqn.pojo.NewsDetail;
//impl包里存放实现类---新闻详情接口的实现类
public class NewsDetailDaoImpl extends BaseDao implements NewsDetailDao {
//查询新闻列表;全查news_detail所有数据
public List<NewsDetail> getNewsDetailList(){
List<NewsDetail> list = new ArrayList<NewsDetail>();
//查询数据库
connection=getConnection();
String sql="select * from news_detail";
try {
pstat=connection.prepareStatement(sql);
//执行sql语句
rs=pstat.executeQuery();
while(rs.next()){
NewsDetail nd=new NewsDetail();
nd.setId(rs.getInt("id"));
nd.setCategoryId(rs.getInt("categoryId"));
nd.setTitle(rs.getString("title"));
nd.setSummary(rs.getString("summary"));
nd.setContent(rs.getString("content"));
nd.setPicPath(rs.getString("picPath"));
nd.setAuthor(rs.getString("author"));
nd.setCreateDate(new Date(rs.getTimestamp("createDate").getTime()));
nd.setModifyDate(new Date(rs.getTimestamp("modifyDate").getTime()));
list.add(nd);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return list;
}
}
//2、//根据id查询内容
public NewsDetail getNewsDetailById(Integer id){
NewsDetail nd=null;
connection = getConnection();
String sql = "select * from news_detail where id=?";
try {
pstat=connection.prepareStatement(sql);
pstat.setInt(1, id);
rs=pstat.executeQuery();
while(rs.next()){
nd=new NewsDetail();
nd.setId(rs.getInt("id"));
nd.setCategoryId(rs.getInt("categoryId"));
nd.setTitle(rs.getString("title"));
nd.setSummary(rs.getString("summary"));
nd.setContent(rs.getString("content"));
nd.setPicPath(rs.getString("picPath"));
nd.setAuthor(rs.getString("author"));
nd.setCreateDate(new Date(rs.getTimestamp("createDate").getTime()));
nd.setModifyDate(new Date(rs.getTimestamp("modifyDate").getTime()));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return nd;
}
实体类:
//创建实体
public class NewsDetail {
private Integer id;
private Integer categoryId;
private String title;
private String summary;
private String content;
private String picPath;
private String author;
private Date createDate;
private Date modifyDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPicPath() {
return picPath;
}
public void setPicPath(String picPath) {
this.picPath = picPath;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
接口:
import java.util.List;
import cn.bdqn.pojo.NewsDetail;
public interface NewsDetailDao {
//新闻详情接口
public List<NewsDetail> getNewsDetailList();
}
测试:
import java.util.List;
import cn.bdqn.dao.impl.NewsDetailDaoImpl;
import cn.bdqn.pojo.NewsDetail;
public class Test {
public static void main(String[] args) {
//全查找测试
NewsDetailDao ndd=new NewsDetailDaoImpl();
List<NewsDetail> list=ndd.getNewsDetailList();
for (NewsDetail nd : list) {
System.out.println(nd.getId()+"--"+nd.getTitle());
}
//根据id查找测试
NewsDetailDao ndd=new NewsDetailDaoImpl();
NewsDetail nd=ndd.getNewsDetailById(3);
// if(nd==null){
// System.out.println("未找到数据");
// }else{
// System.out.println(nd.getId()+"--"+nd.getTitle());
//
// }
}
}
五、查询、添加
需要用到的 类
①、dao包—BaseDao—父类
②、pojo包—NewsDetail—实体
③、impl包—NewsDetailDaoImpl—接口实现类
④、dao包—NewsDetailDao—接口
⑤、dao包—test—测试
1、查询
2、添加
其他类相同
接口:
public int insert(NewsDetail nd);
实现类:
//添加数据,成功返回数字,不成功返回0
public int insert(NewsDetail nd){
int result=0;
connection=getConnection();
String sql="insert into news_detail(categoryId,title,summary,"+
"content,picPath,author,createDate,modifyDate)"+
"values(?,?,?,?,?,?,?,?)";
try {
pstat=connection.prepareStatement(sql);
pstat.setInt(1, nd.getCategoryId());
pstat.setString(2, nd.getTitle());
pstat.setString(3, nd.getSummary());
pstat.setString(4, nd.getContent());
pstat.setString(5, nd.getPicPath());
pstat.setString(6, nd.getAuthor());
pstat.setTimestamp(7, new Timestamp(nd.getCreateDate().getTime()));
pstat.setTimestamp(8, new Timestamp(nd.getModifyDate().getTime()));
//影响了几条数据
result=pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return result;
}
测试:
//添加测试
NewsDetailDao ndd=new NewsDetailDaoImpl();
NewsDetail nd= new NewsDetail();
nd.setCategoryId(2);
nd.setTitle("日本核泄漏");
nd.setSummary("日本将核废水排入大海,遭到周边国家谴责");
nd.setContent("中日韩等沿海及内地国家一致反对,并请菅义伟对此事负责");
nd.setAuthor("admin");
nd.setCreateDate(new Date());
nd.setModifyDate(new Date());
int result =ndd.insert(nd);
System.out.println(result);
六、练习用户表查询和添加
user实体类
public class NewsUser {
private Integer id;
private String userName;
private String password;
private String email;
private Integer userType;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
}
接口实现类
public class NewsUserImpl extends BaseDao implements NewsUserDao{
//查询用户列表
public List<NewsUser> getNewsUserList(){
List<NewsUser> list = new ArrayList<NewsUser>();
//查询数据库
connection=getConnection();
String sql ="select * from news_user";
try {
pstat=connection.prepareStatement(sql);
//执行sql语句
rs=pstat.executeQuery();
while(rs.next()){
NewsUser nu=new NewsUser();
nu.setId(rs.getInt("id"));
nu.setUserName(rs.getString("userName"));
nu.setPassword(rs.getString("password"));
nu.setEmail(rs.getString("email"));
nu.setUserType(rs.getInt("userType"));
list.add(nu);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return list;
}
//通过id查询
public NewsUser getNewsUserById(Integer id){
NewsUser nu=new NewsUser();
connection = getConnection();
String sql = "select * from news_user where id=?";
try {
pstat=connection.prepareStatement(sql);
pstat.setInt(1, id);
rs=pstat.executeQuery();
while(rs.next()){
nu.setId(rs.getInt("id"));
nu.setUserName(rs.getString("userName"));
nu.setPassword(rs.getString("password"));
nu.setEmail(rs.getString("email"));
nu.setUserType(rs.getInt("userType"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return nu;
}
//向用户表添加数据
public int insert(NewsUser nu){
int result=0;
connection=getConnection();
String sql="insert into news_user(userName,password,email,userType)"+
"values(?,?,?,?)";
try {
pstat=connection.prepareStatement(sql);
pstat.setString(1, nu.getUserName());
pstat.setString(2, nu.getPassword());
pstat.setString(3, nu.getEmail());
pstat.setInt(4, nu.getUserType());
result=pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return result;
}
//由于查询时候,都有这段相同的代码,所以提出来
//packageNewsUser( rs, nu);
// private void packageNewsUser(ResultSet rs,NewsUser nu) throws SQLException{
// nu.setId(rs.getInt("id"));
// nu.setUserName(rs.getString("userName"));
// nu.setPassword(rs.getString("password"));
// nu.setEmail(rs.getString("email"));
// nu.setUserType(rs.getInt("userType"));
// }
}
接口
public interface NewsUserDao {
public List<NewsUser> getNewsUserList();
public int insert(NewsUser nu);
public NewsUser getNewsUserById(Integer id);
}
测试
public class NewsUserTest {
public static void main(String[] args) {
NewsUserDao nud=new NewsUserImpl();
// //显示用户表信息
// List<NewsUser> list=nud.getNewsUserList();
// for (NewsUser nu : list) {
// System.out.println(nu.getId()+"--"+nu.getUserName()+"--"
// +nu.getEmail()+nu.getUserType());
// }
//按照id查询
// NewsUser newUser=nud.getNewsUserById(2);
// System.out.println(newUser.getId()+"--"+newUser.getUserName());
//添加数据
NewsUser nu=new NewsUser();
nu.setUserName("App");
nu.setPassword("appplus");
nu.setEmail("App@ton.com");
nu.setUserType(1);
int result=nud.insert(nu);
System.out.println(result);
}
}
七、更新新闻表
//更新新闻的标题测试—先查再更新
//先查再更新某一项,是避免字段被自动填充成空
接口实现类:
//更新--返回影响的条数
public int update(NewsDetail nd){
int result=0;
connection=getConnection();
//id和createDate不更新
String sql="update news_detail set categoryId=?,"
+"title=?,summary=?,content=?,picPath=?,"
+"author=?,modifyDate=? where id=?";
try {
pstat=connection.prepareStatement(sql);
pstat.setInt(1, nd.getCategoryId());
pstat.setString(2, nd.getTitle());
pstat.setString(3, nd.getSummary());
pstat.setString(4, nd.getContent());
pstat.setString(5, nd.getPicPath());
pstat.setString(6, nd.getAuthor());
pstat.setTimestamp(7, new Timestamp(nd.getModifyDate().getTime()));
pstat.setInt(8, nd.getId());
result=pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return result;
}
//按照id查找
public NewsDetail getNewsDetailById(Integer id){
NewsDetail nd=null;
connection=getConnection();
String sql="select * from news_detail where id=?";
try {
pstat=connection.prepareStatement(sql);
pstat.setInt(1, id);
rs=pstat.executeQuery();
while(rs.next()){
nd=new NewsDetail();
nd.setId(rs.getInt("id"));
nd.setCategoryId(rs.getInt("categoryId"));
nd.setTitle(rs.getString("title"));
nd.setSummary(rs.getString("summary"));
nd.setContent(rs.getString("content"));
nd.setPicPath(rs.getString("picPath"));
nd.setAuthor(rs.getString("author"));
nd.setCreateDate(new Date(rs.getTimestamp("createDate").getTime()));
nd.setModifyDate(new Date(rs.getTimestamp("modifyDate").getTime()));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return nd;
}
接口:
public int update(NewsDetail nd);
public NewsDetail getNewsDetailById(Integer id);
测试:
//更新新闻的标题测试--先查再更新
//先查再更新某一项,是避免字段被自动填充成空
NewsDetailDao ndd=new NewsDetailDaoImpl();
NewsDetail nd= ndd.getNewsDetailById(2);
nd.setTitle("OnePice");
int i=ndd.update(nd);
System.out.println(i);
八、更新用户表
接口实现类:
//更新用户表--根据用户修改密码
public int updatePasswordById(String password,Integer id){
int result=0;
connection=getConnection();
String sql="update news_user set password=? where id=?";
try {
pstat=connection.prepareStatement(sql);
pstat.setString(1, password);
pstat.setInt(2, id);
result=pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return result;
}
接口:
public int updatePasswordById(String password,Integer id);
测试:
//用户表更新测试--此时不需要先查询
NewsDetailDao ndd=new NewsDetailDaoImpl();
int i=nud.updatePasswordById("abs123", 3);
System.out.println(i);
八、删除新闻表信息
接口实现类:
//新闻删除--逐条删
public int delete(Integer id){
int result=0;
connection=getConnection();
String sql="delete from news_detail where id=?";
try {
pstat=connection.prepareStatement(sql);
pstat.setInt(1, id);
result=pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
close();
}
return result;
}
接口:
public int delete(Integer id);
测试:
//删除新闻测试
int i=ndd.delete(5);
System.out.println(i);
九、java操作SQL显示到网页上
首先介绍三层
Dao层——-数据层
Services—-业务层
—-转发层
其次需要的类
①、dao包—BaseDao—父类
②、services包—NewsServices—接口
③、impl包—NewsServicesImpl—接口实现类
④、webContent—news—NewsDetailList—JSP文件
接口:
//新闻详情业务接口
public interface NewsServices {
public List<NewsDetail> getNewsDetailList();
}
接口实现类:
package cn.bdqn.services.impl;
import java.util.List;
import cn.bdqn.dao.NewsDetailDao;
import cn.bdqn.dao.impl.NewsDetailDaoImpl;
import cn.bdqn.pojo.NewsDetail;
import cn.bdqn.services.NewsServices;
//接口实现类---Services层存在是因为之后要形成一对多的DAO
public class NewsServicesImpl implements NewsServices{
NewsDetailDao ndd=new NewsDetailDaoImpl();
public List<NewsDetail> getNewsDetailList(){
return ndd.getNewsDetailList();
}
}
JSP文件
<style>
td{
border:black solid 1px
}
</style>
<body>
<table style="border:black solid 1px;border-collapse: collapse;">
<tr>
<td>id</td>
<td>标题</td>
</tr>
<%
NewsServices ns=new NewsServicesImpl();
List<NewsDetail> list=ns.getNewsDetailList();
for(int i=0;i<list.size();i++){
NewsDetail nd=list.get(i);
%>
<tr>
<td><%=nd.getId() %></td>
<td><%=nd.getTitle() %></td>
</tr>
<%}%>
</table>
</body>