连接数据库的步骤:
1、 注册驱动(“com.mysql.jdbc.Driver”)
2、 建立连接(Connection)(“jdbc:mysql://localhost:3306/jdbc”)
3、 创建执行SQL的语句(Statement)
4、 执行语句
5、 处理执行结果(ResultSet)
6、 释放资源
注册驱动:DriverManager.registerDriver(“new com.mysql.jdbc.Driver( )”);
System.setProperty(“jdbc.drivers”,”com.mysql.jdbc.Driver”);
Class.forName(“com.mysql.jdbc.Driver”);--à建议使用—不会对具体的类产生依赖
封装注册、建立连接、释放资源:
publicfinalclass JDBCUtils {
privatestaticfinal Stringurl ="jdbc:mysql://localhost:3306/jdbc";
privatestaticfinal Stringuser ="root";
privatestaticfinal Stringpassword ="admin";
private JDBCUtils() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
thrownew ExceptionInInitializerError(e);
}
}
publicstatic Connection getConnection()throws SQLException {
return DriverManager.getConnection(url,user,password);
}
publicstaticvoid free(Connection conn, Statement st, ResultSet rs) {
try {
if (rs !=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st !=null) {
st.close();
}
}catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (conn !=null) {
conn.close();
}
}catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}
}
对数据库的操作:C(create)R(read)U(update)D(delete)
SQL注入:(PreparedStatement和Statement)
在SQL中包含特殊字符或SQL的关键字(如:‘or 1 or’)时Statement将出现不可预料的结果(出现异常或者查询的结果不正确),可用PreparedStatement来解决;
PreparedStatement相对于Statement的优点:
1、 没有SQL注入的问题
2、 Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出
3、 数据库和驱动可以对PreparedStatement进行优化(只有在相关联的数据库连接没有关闭的情况下有效)
JDBC访问日期的问题:
publicclass CRUD {
publicstaticvoid main(String[] args)throws Exception{
create("tianjian",new Date(),799.0f);
}
publicstaticvoidcreate(String name,Date birthday,float money)throws Exception{
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
conn=JDBCUtils.getConnection();
String sql="insert into user(name,birthday,money)values(?,?,?)";
ps=conn.prepareStatement(sql);
ps.setString(1, name);
ps.setDate(2,new java.sql.Date(birthday.getTime()));
ps.setFloat(3, money);
ps.executeUpdate();
}
finally{
JDBCUtils.free(conn, ps, rs);
}
}