連接數據庫的步驟:
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);
}
}