Java作业八
(一)学习总结
1.用思维导图对本周的学习内容进行总结。
2.通过实验内容中的具体实例说明在执行executeUpdate()方法和executeQuery()方法中使用动态参数时,为什么要使用PreparedStatement接口而不使用Statement,比较使用两种接口的不同之处。
PreparedStatement是Statement的子接口,属于预处理操作,PreparedStatement在操作时是先在数据表中准备好了一条SQL语句,但是此SQL语句的具体内容暂时不设置,而是之后再进行设置。就像是只是占了一条语句的位置,并没有具体的内容。而Statement执行的是一个完整的SQL语句,在程序中往往要使用拼凑的SQL语句完成。由于PreparedStatement对象已经预编译过,所以其执行速度要高于Statement对象。因此要执行多次执行的SQL语句经常使用PreparedStatement对象操作。
Statement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Sta{
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver;"
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
public static final String DBUSER = "root";
public static final String DBPASS = "mysqladmin";
public static void main(String[] args) throws Exception{
Connection conn = null;
Statement stmt = null;
String sql = "INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('李兴华','www.mldn.cn',30,'男','2008-08-27')";
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
stmt = conn.createStatement();
stmt.executeUpdate(sql);
conn.close();
}
}
PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Pre{
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver;"
public static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
public static final String DBUSER = "root";
public static final String DBPASS = "mysqladmin";
public static void main(String[] args) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
String name = "李兴华";
String password = "www.mldnjava.cn";
int age = 30;
String sex = "男";
String birthday = "2007-08-27";
java.util.Date temp = null;
temp = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
java.sql.Date.bir = new java.sql.Date(temp.getTime());
String sql = "INSERT INTO user(name,password,age,sex,birthday)"+"VALUES(?,?,?,?,?)";
Class.forName(DBRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,name);
pstmt.setString(2,password);
pstmt.setInt(3,age);
pstmt.setString(4,sex);
pstmt.setDate(5,bir);
pstmt.executeUpdate();
pstmt.close();
conn.close();
}
}
3.其他需要总结的内容。
预处理就是用“?”进行占位。例:
String sql = "INSERT INTO user(name,password,age,sex,birthday)"
+"VALUES(?,?,?,?,?)";
模糊查询:
在模糊查询中使用“%”表示通配符,但是这个通配符是要在设置具体查询内容(setXxx()方法调用)时才使用。
开发中很少使用Statement对象进行操作,使用PreparedStatement。
在JDBC代码中一般习惯分辨按照顺序关闭,即先打开的后关闭。
(二)实验总结
实验内容:
使用JDBC实现实验七的宠物商店
完成实验内容,代码上传到码云,注意,务必将创建数据库的脚本文件随项目文件一起上传,在随笔中分析程序设计思路,用PowerDesigner画出类图结构,并对完成实验内容过程中遇到的问题、解决方案和思考等进行归纳总结,注意代码中必须有必要的注释。
思路:根据老师给的FruitStore改写,连接数据库。