JDBC(Java Data Base Connection)的作用是連接數據庫
先看下jdbc連接SQLServer數據庫的簡單例子
代碼實現(FirstJDBC):
- package com.jdbc;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- public class FirstJDBC {
- public static void main(String[] args)
- {
- //調用連接數據庫的操作
- Connection con = createConnection();
- }
- /**
- * JDBC 建立 SQL Server數據庫連接
- */
- private static Connection createConnection() {
- //定義加載驅動程序
- String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
- //定義 連接 服務器 和 數據庫sample
- String dbURL = "jdbc:sqlserver://localhost:1433; DataBaseName = sample1" ;
- //默認用戶名,不要用windows默認身份驗證
- String userName = "sa" ;
- String userPassword = "zhichao" ;
- Connection connection = null ;
- Statement sta = null ;
- try {
- //正式加載驅動
- Class.forName(driverName);
- //開始連接
- connection = DriverManager.getConnection(dbURL, userName, userPassword);
- System.out.println("Connection Success !");
- //向數據庫中執行SQL語句
- sta = connection.createStatement() ;
- ResultSet rs = sta.executeQuery("SELECT id,name,height From Table_1");
- while(rs.next())
- {
- int id = rs.getInt("id");
- String name = rs.getString("name");
- float height = rs.getFloat("height");
- System.out.println("id = "+id+" name = "+name+" height = "+height);
- }
- } catch (Exception e) {
- System.out.println("Connection Fail !");
- e.printStackTrace() ;
- }
- /**
- * 關閉數據庫
- * @param connection
- */
- finally
- {
- try {
- if (null != sta)
- {
- sta.close() ;
- sta = null;
- System.out.println("Statement 關閉成功");
- }
- if (null != connection)
- {
- connection.close() ;
- connection = null;
- System.out.println("Connection 關閉成功");
- }
- } catch (Exception e) {
- e.printStackTrace() ;
- }
- }
- return connection ;
- }
- }
小結:
要寫一個jdbc程序,先要加載相應數據庫的驅動程序,驅動程序最好放在你建的工程里面,可以在你的工程下面建一個 lib文件夾以存儲外部的jar文件,這樣的話把你的工程拷貝到別的計算機運行,仍能成功執行。
jdbc代碼一般步驟:
1)加載外部驅動程序(jar包)
2)正式加載驅動程序 (Class.forName(driverName) )
3)獲取connection連接 (在jdk中的sql包中,只提供了一個類那就是DriverManeger,通過調用它的靜態方法getConnection(),可以得到以數據庫的連接
4)創建sql語句的聲明(Statement),執行sql語句(查詢),遍歷結果集
5)關閉數據庫連接(一般用finally{}來處理,或者調用方法的形式來完成,關閉之前先判斷你要關閉的對象連接是否為空,如果空那會拋異常,所以先判斷)
------------------------------------- ------------------------------------- ------------------------Data Access Objects-------------------- ------------------------------------------- ---------------------------
使用 DAO模式 來對數據庫做增刪改查操作
這種模式可以大概分為三個層:1.DAO層 2.服務層 3.表現層
1)表現層 :相當於客戶端用來查看,提交信息的角色
2)服務層 :是表現層和DAO層的紐帶,其實也沒干什么事就是通知消息的角色
3)DAO :真正要做事的角色(對數據庫的某些操作)
舉個生活中的例子:
就好比你去餐廳吃飯,你充當一個 (表現層)的角色,然后有美女服務員(服務層),問你需要吃什么東西,給你下一張訂單,讓你填。之后服務員把訂單傳到 廚師(DAO層)那里,具體操作廚師會搞定,一段時間后廚師把做好的食物傳給服務員,服務員把食物在傳給客戶,這些操作就算基本完成了。
執行順序: 表現層-->服務層-->DAO層-->返回服務層-->返回表現層
來看看實現DAO模式的UML圖:
代碼實現:
1.Bean文件,在這主要作用(有點像中介存儲的角色):當從數據庫拿出數據后,一個個set到該類里,進行賦值,然后把該對象放到集合中,之后再get出來
Student.java
- package com.myjdbc.bean;
- public class Student {
- private Integer stuId;
- private String stuName ;
- private Integer stuAge;
- private String stuTel ;
- private String stuAddress ;
- private Integer groupId;
- public Integer getStuId() {
- return stuId;
- }
- public void setStuId(Integer stuId) {
- this.stuId = stuId;
- }
- public String getStuName() {
- return stuName;
- }
- public void setStuName(String stuName) {
- this.stuName = stuName;
- }
- public Integer getStuAge() {
- return stuAge;
- }
- public void setStuAge(Integer stuAge) {
- this.stuAge = stuAge;
- }
- public String getStuTel() {
- return stuTel;
- }
- public void setStuTel(String stuTel) {
- this.stuTel = stuTel;
- }
- public String getStuAddress() {
- return stuAddress;
- }
- public void setStuAddress(String stuAddress) {
- this.stuAddress = stuAddress;
- }
- public Integer getGroupId() {
- return groupId;
- }
- public void setGroupId(Integer groupId) {
- this.groupId = groupId;
- }
- }
2.java連接數據庫的基本操作及關閉,封裝在一個類中
JDBCUtils.java
- package com.myjdbc.utils;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- public class JDBCUtils {
- /**
- * 獲取連接
- *
- */
- public static Connection getConnection()
- {
- String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
- String url = "jdbc:sqlserver://localhost:1433; DataBaseName = studentManager";
- String user = "sa" ;
- String password = "zhichao";
- Connection con = null ;
- try {
- Class.forName(driverName);
- con = DriverManager.getConnection(url, user, password);
- System.out.println("success");
- } catch (Exception e) {
- e.printStackTrace();
- }
- return con ;
- }
- /**
- * 關閉連接
- */
- public static void free(ResultSet rs, Statement sta , Connection con)
- {
- try {
- if(null != rs)
- {
- rs.close();
- rs = null ;
- }
- if(null != sta)
- {
- sta.close();
- sta = null ;
- }
- if(null != con)
- {
- con.close();
- con = null ;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
3.定義一個DAO接口
StudentDAO.java
- package com.myjdbc.dao;
- import java.util.Set;
- import com.myjdbc.bean.Student ;
- public interface StudentDAO {
- public int addStudent(Student student) ;
- public int deleteStudent(String name);
- public int updateStudent(String name);
- public Student findStudent(String name);
- public Set<Student> findAll();
- }
4.實現DAO接口的類,具體DAO,做重要工作的類
ConcreteStudentDao.java
- package com.myjdbc.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.HashSet;
- import java.util.Set;
- import com.myjdbc.bean.Student;
- import com.myjdbc.dao.StudentDAO;
- import com.myjdbc.utils.JDBCUtils;
- public class ConcreteStudentDao implements StudentDAO{
- //增加一個學生
- public int addStudent(Student student)
- {
- Connection con = null ;
- PreparedStatement ps = null ;
- int i = 0 ;
- try
- {
- con = JDBCUtils.getConnection();
- String sql = "insert into student(stuName,stuAge,stuTel,stuAddress,groupId) values(?,?,?,?,?)";
- ps = con.prepareStatement(sql);
- ps.setString(1, student.getStuName());
- ps.setInt(2, student.getStuAge());
- ps.setString(3, student.getStuTel());
- ps.setString(4, student.getStuAddress());
- ps.setInt(5, student.getGroupId());
- i = ps.executeUpdate() ;
- }
- catch(SQLException e)
- {
- throw new DAOException(e.getMessage(),e);
- }
- finally
- {
- JDBCUtils.free(null, ps, con);
- }
- return i;
- }
- //刪除一個學生
- public int deleteStudent(String name)
- {
- Connection con = null ;
- PreparedStatement ps = null ;
- int i = 0 ;
- try
- {
- con = JDBCUtils.getConnection();
- String sql = "delete from student where stuName =?";
- ps = con.prepareStatement(sql);
- ps.setString(1, name);
- i = ps.executeUpdate() ;
- }
- catch(SQLException e)
- {
- throw new DAOException(e.getMessage(),e);
- }
- finally
- {
- JDBCUtils.free(null, ps, con);
- }
- return i;
- }
- //修改一個學生
- public int updateStudent(String name)
- {
- Connection con = null ;
- PreparedStatement ps = null ;
- int i = 0 ;
- try
- {
- con = JDBCUtils.getConnection();
- String sql = "update student set stuAge=stuAge+1 where stuName =?";
- ps = con.prepareStatement(sql);
- ps.setString(1, name);
- i = ps.executeUpdate() ;
- }
- catch(SQLException e)
- {
- throw new DAOException(e.getMessage(),e);
- }
- finally
- {
- JDBCUtils.free(null, ps, con);
- }
- return i;
- }
- //查詢一行
- public Student findStudent(String name)
- {
- Connection con = null ;
- PreparedStatement ps = null ;
- Student stu = null ;
- ResultSet rs = null;
- try
- {
- con = JDBCUtils.getConnection();
- String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student where stuName =?";
- ps = con.prepareStatement(sql);
- ps.setString(1, name);
- rs = ps.executeQuery() ;
- stu = new Student();
- while(rs.next())
- {
- stu.setStuName(rs.getString(1));
- stu.setStuAge(rs.getInt(2));
- stu.setStuTel(rs.getString(3));
- stu.setStuAddress(rs.getString(4));
- stu.setGroupId(rs.getInt(5));
- }
- }
- catch(SQLException e)
- {
- throw new DAOException(e.getMessage(),e);
- }
- finally
- {
- JDBCUtils.free(rs, ps, con);
- }
- return stu;
- }
- //查詢所有
- public Set<Student> findAll()
- {
- Connection con = null ;
- PreparedStatement ps = null ;
- Student stu = null ;
- ResultSet rs = null;
- Set<Student> set = null ;
- try
- {
- con = JDBCUtils.getConnection();
- String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student";
- ps = con.prepareStatement(sql);
- set = new HashSet<Student>() ;
- rs = ps.executeQuery() ;
- while(rs.next())
- {
- stu = new Student();
- stu.setStuName(rs.getString(1));
- stu.setStuAge(rs.getInt(2));
- stu.setStuTel(rs.getString(3));
- stu.setStuAddress(rs.getString(4));
- stu.setGroupId(rs.getInt(5));
- set.add(stu);
- }
- }
- catch(SQLException e)
- {
- throw new DAOException(e.getMessage(),e);
- }
- finally
- {
- JDBCUtils.free(rs, ps, con);
- }
- return set;
- }
- }
5.自定義異常 繼承了運行時異常,具體操作讓父類實現
DAOException.java
- package com.myjdbc.dao;
- /**
- * 自定義異常
- * @author Administrator
- *
- */
- public class DAOException extends RuntimeException {
- public DAOException()
- {
- super();
- }
- public DAOException(String messege,Throwable cause)
- {
- super(messege,cause);
- }
- public DAOException(String messege)
- {
- super(messege);
- }
- public DAOException(Throwable cause)
- {
- super(cause);
- }
- }
6定義一個服務類(服務層),本來還要定義一個接口,這里簡寫了,客戶與DAO的紐帶,持有DAO對象的引用
StudentService.java
- package com.myjdbc.service;
- import java.util.Set;
- import com.myjdbc.bean.Student;
- import com.myjdbc.dao.StudentDAO;
- import com.myjdbc.dao.ConcreteStudentDao;
- public class StudentService {
- StudentDAO sd = new ConcreteStudentDao();
- public int add(Student student)
- {
- return this.sd.addStudent(student);
- }
- public int delete(String name)
- {
- return this.sd.deleteStudent(name);
- }
- public int update(String name)
- {
- return this.sd.updateStudent(name);
- }
- public Student find(String name)
- {
- return this.sd.findStudent(name);
- }
- public Set<Student> findAll()
- {
- return this.sd.findAll();
- }
- }
7.定義一個測試類,相當於 (表現層)
Client.java
- package com.myjdbc.test;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Set;
- import com.myjdbc.bean.Student;
- import com.myjdbc.service.StudentService;
- public class Client {
- public static void main(String[] args)
- {
- Student stu = new Student();
- Set<Student> set = new HashSet<Student>();
- // stu.setStuName("zhangsan");
- // stu.setStuAge(20);
- // stu.setStuTel("18779157911");
- // stu.setStuAddress("china");
- // stu.setGroupId(1);
- StudentService ss = new StudentService();
- //System.out.println(ss.add(stu));
- //System.out.println(ss.delete("aa"));
- //System.out.println(ss.update("bb"));
- //stu = ss.find("cc");
- //System.out.println(stu.getStuName() +" " +stu.getStuAge()+" "+stu.getStuTel()+" "+stu.getStuAddress()+" "+stu.getGroupId());
- set = ss.findAll() ;
- Iterator<Student> iterator = set.iterator();
- while(iterator.hasNext())
- {
- Student student = (Student)iterator.next() ;
- System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());
- }
- }
- }