JDBC
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class QueryDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
try {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 创造连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cartoondb", "root", "123456");
// 预编译sql语句
pst = conn.prepareStatement("select * from ?");
pst.setString(1, "cartoon");
// 打印sql语句
// com.mysql.jdbc.JDBC4PreparedStatement@5afa04c: select * from cartoon
System.out.println(pst.toString());
rst = pst.executeQuery();
while (rst.next()) {
System.out.print("1===" + rst.getInt(1) + "\t");
System.out.print("2===" + rst.getInt(2) + "\t");
System.out.println("3===" + rst.getString(3));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭连接
try {
if (rst != null) {
rst.close();
}
if (pst != null) {
pst.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
rst = null;
pst = null;
conn = null;
}
}
}
}
JDBC里的Date类型数据转换
由于request得到的数据都是字符串类型
所以需要先转换 String -->Date --> Date
String date = requeat.getParameter("Date");
Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
JDBC的mysql链接的三个数据:
Class.forName:com.mysql.jdbc.Driver(加载驱动)
url:jdbc:mysql://localhost:3306/数据库名字
user:用户名字
pwd:用户密码
Java8以后就不用加载驱动了,会自动加载!
Properties properties = new Properties();
//读取的都是src下的文件,根据的是根项目
InputStream is = new FileInputStream("src/jdbc.properties");
//使用类加载器,去读取src底下的资源文件。 后面在servlet
//InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(is);
ps.getProperty(key);
JDBC需要用的三个主要类
- Connection:数据库连接
- PreparedStatement:准备sql语句,父类:Statement(不安全)
- Result:结果集
结果集ResultSet即使里面没有数据,也不等于null
rs.getString(int countx);从1开始
rs.first();:拿出结果集里的第一个数据,返回布尔值
自建数据库连接池
需要先实现DataSource接口,并重写getConnection()方法
为了可归还链接,需要用到装饰者模式
实现Connection接口,并重写getConection()方法和prepareStatement(String sql)方法
return conn.prepareStatement(sql);
返回接口的结果
DBCP
导包:commons-dbcp-1.4.jar commons-pool-1.5.6.jar mysql-connector-java-5.1.20-bin.jar
不使用配置文件
1.获得连接池对象
BasicDataSource dataSource = new BasicDataSource();
使用配置文件
- 得到可读取配置文件的对象
BasicDataSourceFactory factory = new BasicDataSourceFactory(); - 创造读取文档的流
Properties properties = new Properties();
InputStream is = new FileInputStream(“src/dbcpconfig.properties”);
properties.load(is); - 创建数据库连接池:
DataSource dataSource = factory.createDataSource(properties);
C3P0
不使用配置文件
ComboPooledDataSource dataSource = new CombopooledDataSource();
不可以使用setProperties(Properties properties);来给数据连接池赋值
使用配置文件
ComPooledDataSource dataSource = new ComBopooledDataSource();
建议使用xml文档,不用再写些什么,帮你写好了!直接new完就行,括号里面可以写数据库的名字,不写就用默认的
DButil
QueryRunner query = new QueryRunner(DataSource);
-
单个数据:
BeanHandler<Bean>(bean.class)
-
多个数据:
BeanListHandler<Bean>(Bean.class)
-
用于返回计数的数据
用于处理 平均值 、 总的个数。
Long result = (Long) runner.query("SELECT COUNT() FROM stu" , new ScalarHandler());*
其它
- Object …args:代表多个参数,个数不确定
- 元数据
用于描述数据的数据,再JavaEE中有三种:数据库元数据(DataBaseMetaData),参数元数据(ParameterMetaData),结果集元数据(ResultSetMetaData)。
代码描述:
//为了防止多写参数,所以以“?”出现的次数来添加数据
ParameterMetaData metaData = ps.getParameterMetaData();//ps是PreparedStatement类型的
int count = metaData.getParameterCount();
异常
- 打印异常:
e.printStrackTrace();
Cookie和Session
cookie只能存储32位
有一个默认cookie,用于存储会话id
new Cookie(‘JSESSIONID’, session.getId());
创建session的注意事项
HttpSession session = request.getSession(boolean b);
默认为true,不存在便创建一个新的,存在便获得
false:不在也不创建了,存在便获得
XML文档操作
package com.ytl.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.ytl.entity.User;
/**
* 操作心愿单xml文档的工具类
*
* @author 余腾龙
*
*/
public class LoveCartoonXml {
private static Document doc = null;
private static Element rootElement = null;
static {
try {
// 得到整个文档对象
doc = new SAXReader().read(new File("D:\\SZ\\JAVA_Web\\study_cartoon\\WebContent\\love\\love.xml"));// love/love.xml
// 得到根目录
rootElement = doc.getRootElement();
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 得到xml文档的心愿单数据
*
* @param id
* @return 字符串id,例如1,5,7
* @throws DocumentException
*/
public static String getLoveId(String id) {
Element e = (Element) doc.selectSingleNode("/users/user[@id='"+id+"']");
String str = e.element("love_id").getText();
String[] tmp = str.split("#ytl#");
String loves = Arrays.toString(tmp);
//去掉空格
loves = loves.replaceAll(" ", "");
return loves.substring(1, loves.length() - 1);
// int userId = Integer.parseInt(id);
// List<Element> list = rootElement.elements();
// Element userElement = list.get(userId - 1);
// if (userId == Integer.parseInt(userElement.attributeValue("id"))) {
// Element loveIdElement = userElement.element("love_id");
// String loveid = loveIdElement.getText();
// String[] tmp = loveid.split("#ytl#");
// String loves = Arrays.toString(tmp);
// return loves.substring(1, loves.length() - 1);
// } else {
// for (Element e : list) {
// if (userId == Integer.parseInt(e.attributeValue("id"))) {
// Element loveIdElement = e.element("love_id");
// String loveid = loveIdElement.getText();
// String[] tmp = loveid.split("#ytl#");
// String loves = Arrays.toString(tmp);
// return loves.substring(1, loves.length() - 1);
// }
// }
// }
}
/**
* 向xml文档重写心愿单,传入封装好的数据
*
* @param id
* @param newLoveId
* @throws DocumentException
* @throws IOException
*/
public static void setLoveId(String id, String[] loves) throws DocumentException, IOException {
//开始封装数据
String tmp1 = StringAndToArrty.arrToString(loves);
String newLoveId = tmp1.replaceAll(",", "#ytl#")+"#ytl#";
//封装完成后开始传入数据
Element e = (Element) doc.selectSingleNode("/users/user[@id='"+id+"']");
Element LoveIdElement = e.element("love_id");
//传入数据
String tmp0 = LoveIdElement.getText();
LoveIdElement.setText(tmp0+newLoveId);
// 指定文件输出的位置
FileOutputStream out = new FileOutputStream("D:\\SZ\\JAVA_Web\\study_cartoon\\WebContent\\love/love.xml");
// 指定写xml的格式
// OutputFormat format = OutputFormat.createCompactFormat(); //紧凑的格式.去除空格换行.项目上线的时候
OutputFormat format = OutputFormat.createPrettyPrint(); // 漂亮的格式.有空格和换行.开发调试的时候
/**
* 2.指定生成的xml文档的编码 同时影响了xml文档保存时的编码 和 xml文档声明的encoding的编码(xml解析时的编码) 结论:
* 使用该方法生成的xml文档避免中文乱码问题。
*/
format.setEncoding("utf-8");
// 1.创建写出对象
XMLWriter writer = new XMLWriter(out, format);
// 2.写出对象
writer.write(doc);
// 3.关闭流
writer.close();
}
/**
* 向心愿单xml文件里添加新添加的user,需要传入新注册的user对象
*
* @param user
* @throws DocumentException
*/
public static void addUserToLoveXml(String userName, int id) throws DocumentException {
Document doc = new SAXReader().read(new File("D:\\SZ\\JAVA_Web\\study_cartoon\\WebContent\\love/love.xml"));
Element rootElement = doc.getRootElement();
List<Element> list = rootElement.elements();
Element tmp1 = rootElement.addElement("user");
tmp1.addAttribute("id", id + "");
Element nameElement = tmp1.addElement("name");
nameElement.setText(userName);
tmp1.addElement("love_id");
}
}
ServletUpLoad上传文件
private boolean addCartoon(HttpServletRequest request, Cartoon ct, PrintWriter pw) {
System.out.println("add");
// 判断表单里是否含有文件,判断的是 enctype="multipart/form-data"
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 上传文件所放的文件夹
String uploadFilePath = getServletContext().getRealPath("Images");
System.out.println("上传文件所放的文件夹+uploadFilePath=="+uploadFilePath);
if (isMultipart) {// 判断是否是普通表单
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024 * 5);// 设置文件最大值为5MB
// 解析form表单
try {
List<FileItem> items = upload.parseRequest(request);
boolean isUnallowedType = false; // 是否为不允许的文件类型
File saveFile = null;
for (FileItem item : items) {
if (item.isFormField()) {// 是否是普通表单字段
String fieldName = item.getFieldName(); // 表单字段的name属性值
BeanUtils.setProperty(ct, fieldName, item.getString("utf-8"));
} else { // 上传的文件
// 文件的名字
String fileName = item.getName();
System.out.println("文件的名字fileName==:"+fileName);
if (fileName.length() > 0) {
// 上传的类型
List<String> fileType = Arrays.asList("gif", "jpg", "jpeg", "png");
int index = fileName.lastIndexOf(".");
String ext = index == -1 ? "" : fileName.substring(index + 1).toLowerCase();
if (fileType.contains(ext)) {// 判断文件类型是否在允许范围内
//设置写入文件的路径
File fullFile = new File(UUID.randomUUID()+ext);
saveFile = new File(uploadFilePath, fullFile.getName());
try {
item.write(saveFile);// 上传图片
} catch (Exception e) {
e.printStackTrace();
}
ct.setPic(saveFile.getName());
System.out.println(ct);
} else {
isUnallowedType = false;
}
}
}
}
return isUnallowedType;
} catch (FileUploadException e) {
e.printStackTrace();
pw.write("<script>alert('上传失败,最大限制为5MB!')</script>");
pw.print("<script>location.href='adminpages/addCartoon.jsp'</script>");
System.out.println("上传失败,最大限制为5MB!");
} catch (IllegalAccessException | InvocationTargetException | UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println("漫画参数添加失败!");
pw.write("<script>alert('漫画参数添加失败!')</script>");
pw.print("<script>location.href='adminpages/addCartoon.jsp'</script>");
}
}
return false;
// try {
//
// // 注册自己的日期转换器
// ConvertUtils.register(new MyDateConverter(), Date.class);
// // 转化数据
// //Map map = request.getParameterMap();
// Cartoon ct = new Cartoon();
// BeanUtils.populate(ct, map);
// } catch (Exception e) {
// e.printStackTrace();
// }
}
MyDateConverter
package com.ytl.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
public class MyDateConverter implements Converter{
@Override
// 将value 转换 c 对应类型
// 存在Class参数目的编写通用转换器,如果转换目标类型是确定的,可以不使用c 参数
public Object convert(Class c, Object value) {
String strVal = (String) value;
// 将String转换为Date --- 需要使用日期格式化
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = dateFormat.parse(strVal);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
补充
QueryRunner 里的insert方法
QueryRunner实例化不传入连接池时,就用query.update(Connect conn, sql, BeanListHander);
${param.name}得到表单里的值