JDBC(Java Data Base Connection)的作用是连接数据库

先看下jdbc连接SQLServer数据库的简单例子

代码实现(FirstJDBC):

  1. package com.jdbc;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. public class FirstJDBC {
  7. public static void main(String[] args)
  8. {
  9. //调用连接数据库的操作
  10. Connection con = createConnection();
  11. }
  12. /**
  13. * JDBC 建立 SQL Server数据库连接
  14. */
  15. private static Connection createConnection() {
  16. //定义加载驱动程序
  17. String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
  18. //定义 连接 服务器 和 数据库sample
  19. String dbURL = "jdbc:sqlserver://localhost:1433; DataBaseName = sample1" ;
  20. //默认用户名,不要用windows默认身份验证
  21. String userName = "sa" ;
  22. String userPassword = "zhichao" ;
  23. Connection connection = null ;
  24. Statement sta = null ;
  25. try {
  26. //正式加载驱动
  27. Class.forName(driverName);
  28. //开始连接
  29. connection = DriverManager.getConnection(dbURL, userName, userPassword);
  30. System.out.println("Connection Success !");
  31. //向数据库中执行SQL语句
  32. sta = connection.createStatement() ;
  33. ResultSet rs = sta.executeQuery("SELECT id,name,height From Table_1");
  34. while(rs.next())
  35. {
  36. int id = rs.getInt("id");
  37. String name = rs.getString("name");
  38. float height = rs.getFloat("height");
  39. System.out.println("id = "+id+" name = "+name+" height = "+height);
  40. }
  41. } catch (Exception e) {
  42. System.out.println("Connection Fail !");
  43. e.printStackTrace() ;
  44. }
  45. /**
  46. * 关闭数据库
  47. * @param connection
  48. */
  49. finally
  50. {
  51. try {
  52. if (null != sta)
  53. {
  54. sta.close() ;
  55. sta = null;
  56. System.out.println("Statement 关闭成功");
  57. }
  58. if (null != connection)
  59. {
  60. connection.close() ;
  61. connection = null;
  62. System.out.println("Connection 关闭成功");
  63. }
  64. } catch (Exception e) {
  65. e.printStackTrace() ;
  66. }
  67. }
  68. return connection ;
  69. }
  70. }

小结:

要写一个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

  1. package com.myjdbc.bean;
  2. public class Student {
  3. private Integer stuId;
  4. private String stuName ;
  5. private Integer stuAge;
  6. private String stuTel ;
  7. private String stuAddress ;
  8. private Integer groupId;
  9. public Integer getStuId() {
  10. return stuId;
  11. }
  12. public void setStuId(Integer stuId) {
  13. this.stuId = stuId;
  14. }
  15. public String getStuName() {
  16. return stuName;
  17. }
  18. public void setStuName(String stuName) {
  19. this.stuName = stuName;
  20. }
  21. public Integer getStuAge() {
  22. return stuAge;
  23. }
  24. public void setStuAge(Integer stuAge) {
  25. this.stuAge = stuAge;
  26. }
  27. public String getStuTel() {
  28. return stuTel;
  29. }
  30. public void setStuTel(String stuTel) {
  31. this.stuTel = stuTel;
  32. }
  33. public String getStuAddress() {
  34. return stuAddress;
  35. }
  36. public void setStuAddress(String stuAddress) {
  37. this.stuAddress = stuAddress;
  38. }
  39. public Integer getGroupId() {
  40. return groupId;
  41. }
  42. public void setGroupId(Integer groupId) {
  43. this.groupId = groupId;
  44. }
  45. }

2.java连接数据库的基本操作及关闭,封装在一个类中

JDBCUtils.java

  1. package com.myjdbc.utils;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. public class JDBCUtils {
  7. /**
  8. * 获取连接
  9. *
  10. */
  11. public static Connection getConnection()
  12. {
  13. String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
  14. String url = "jdbc:sqlserver://localhost:1433; DataBaseName = studentManager";
  15. String user = "sa" ;
  16. String password = "zhichao";
  17. Connection con = null ;
  18. try {
  19. Class.forName(driverName);
  20. con = DriverManager.getConnection(url, user, password);
  21. System.out.println("success");
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. return con ;
  26. }
  27. /**
  28. * 关闭连接
  29. */
  30. public static void free(ResultSet rs, Statement sta , Connection con)
  31. {
  32. try {
  33. if(null != rs)
  34. {
  35. rs.close();
  36. rs = null ;
  37. }
  38. if(null != sta)
  39. {
  40. sta.close();
  41. sta = null ;
  42. }
  43. if(null != con)
  44. {
  45. con.close();
  46. con = null ;
  47. }
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }

3.定义一个DAO接口

StudentDAO.java

  1. package com.myjdbc.dao;
  2. import java.util.Set;
  3. import com.myjdbc.bean.Student ;
  4. public interface StudentDAO {
  5. public int addStudent(Student student) ;
  6. public int deleteStudent(String name);
  7. public int updateStudent(String name);
  8. public Student findStudent(String name);
  9. public Set<Student> findAll();
  10. }

4.实现DAO接口的类,具体DAO,做重要工作的类

ConcreteStudentDao.java

  1. package com.myjdbc.dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.HashSet;
  7. import java.util.Set;
  8. import com.myjdbc.bean.Student;
  9. import com.myjdbc.dao.StudentDAO;
  10. import com.myjdbc.utils.JDBCUtils;
  11. public class ConcreteStudentDao implements StudentDAO{
  12. //增加一个学生
  13. public int addStudent(Student student)
  14. {
  15. Connection con = null ;
  16. PreparedStatement ps = null ;
  17. int i = 0 ;
  18. try
  19. {
  20. con = JDBCUtils.getConnection();
  21. String sql = "insert into student(stuName,stuAge,stuTel,stuAddress,groupId) values(?,?,?,?,?)";
  22. ps = con.prepareStatement(sql);
  23. ps.setString(1, student.getStuName());
  24. ps.setInt(2, student.getStuAge());
  25. ps.setString(3, student.getStuTel());
  26. ps.setString(4, student.getStuAddress());
  27. ps.setInt(5, student.getGroupId());
  28. i = ps.executeUpdate() ;
  29. }
  30. catch(SQLException e)
  31. {
  32. throw new DAOException(e.getMessage(),e);
  33. }
  34. finally
  35. {
  36. JDBCUtils.free(null, ps, con);
  37. }
  38. return i;
  39. }
  40. //删除一个学生
  41. public int deleteStudent(String name)
  42. {
  43. Connection con = null ;
  44. PreparedStatement ps = null ;
  45. int i = 0 ;
  46. try
  47. {
  48. con = JDBCUtils.getConnection();
  49. String sql = "delete from student where stuName =?";
  50. ps = con.prepareStatement(sql);
  51. ps.setString(1, name);
  52. i = ps.executeUpdate() ;
  53. }
  54. catch(SQLException e)
  55. {
  56. throw new DAOException(e.getMessage(),e);
  57. }
  58. finally
  59. {
  60. JDBCUtils.free(null, ps, con);
  61. }
  62. return i;
  63. }
  64. //修改一个学生
  65. public int updateStudent(String name)
  66. {
  67. Connection con = null ;
  68. PreparedStatement ps = null ;
  69. int i = 0 ;
  70. try
  71. {
  72. con = JDBCUtils.getConnection();
  73. String sql = "update student set stuAge=stuAge+1  where stuName =?";
  74. ps = con.prepareStatement(sql);
  75. ps.setString(1, name);
  76. i = ps.executeUpdate() ;
  77. }
  78. catch(SQLException e)
  79. {
  80. throw new DAOException(e.getMessage(),e);
  81. }
  82. finally
  83. {
  84. JDBCUtils.free(null, ps, con);
  85. }
  86. return i;
  87. }
  88. //查询一行
  89. public Student findStudent(String name)
  90. {
  91. Connection con = null ;
  92. PreparedStatement ps = null ;
  93. Student stu = null ;
  94. ResultSet rs = null;
  95. try
  96. {
  97. con = JDBCUtils.getConnection();
  98. String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student where stuName =?";
  99. ps = con.prepareStatement(sql);
  100. ps.setString(1, name);
  101. rs = ps.executeQuery() ;
  102. stu = new Student();
  103. while(rs.next())
  104. {
  105. stu.setStuName(rs.getString(1));
  106. stu.setStuAge(rs.getInt(2));
  107. stu.setStuTel(rs.getString(3));
  108. stu.setStuAddress(rs.getString(4));
  109. stu.setGroupId(rs.getInt(5));
  110. }
  111. }
  112. catch(SQLException e)
  113. {
  114. throw new DAOException(e.getMessage(),e);
  115. }
  116. finally
  117. {
  118. JDBCUtils.free(rs, ps, con);
  119. }
  120. return stu;
  121. }
  122. //查询所有
  123. public Set<Student> findAll()
  124. {
  125. Connection con = null ;
  126. PreparedStatement ps = null ;
  127. Student stu = null ;
  128. ResultSet rs = null;
  129. Set<Student> set = null ;
  130. try
  131. {
  132. con = JDBCUtils.getConnection();
  133. String sql = "select stuName,stuAge,stuTel,stuAddress,groupId from student";
  134. ps = con.prepareStatement(sql);
  135. set = new HashSet<Student>() ;
  136. rs = ps.executeQuery() ;
  137. while(rs.next())
  138. {
  139. stu = new Student();
  140. stu.setStuName(rs.getString(1));
  141. stu.setStuAge(rs.getInt(2));
  142. stu.setStuTel(rs.getString(3));
  143. stu.setStuAddress(rs.getString(4));
  144. stu.setGroupId(rs.getInt(5));
  145. set.add(stu);
  146. }
  147. }
  148. catch(SQLException e)
  149. {
  150. throw new DAOException(e.getMessage(),e);
  151. }
  152. finally
  153. {
  154. JDBCUtils.free(rs, ps, con);
  155. }
  156. return set;
  157. }
  158. }

5.自定义异常 继承了运行时异常,具体操作让父类实现

DAOException.java

  1. package com.myjdbc.dao;
  2. /**
  3. * 自定义异常
  4. * @author Administrator
  5. *
  6. */
  7. public class DAOException extends RuntimeException {
  8. public DAOException()
  9. {
  10. super();
  11. }
  12. public DAOException(String messege,Throwable cause)
  13. {
  14. super(messege,cause);
  15. }
  16. public DAOException(String messege)
  17. {
  18. super(messege);
  19. }
  20. public DAOException(Throwable cause)
  21. {
  22. super(cause);
  23. }
  24. }

6定义一个服务类(服务层),本来还要定义一个接口,这里简写了,客户与DAO的纽带,持有DAO对象的引用

StudentService.java

  1. package com.myjdbc.service;
  2. import java.util.Set;
  3. import com.myjdbc.bean.Student;
  4. import com.myjdbc.dao.StudentDAO;
  5. import com.myjdbc.dao.ConcreteStudentDao;
  6. public class StudentService {
  7. StudentDAO sd = new ConcreteStudentDao();
  8. public int add(Student student)
  9. {
  10. return this.sd.addStudent(student);
  11. }
  12. public int delete(String name)
  13. {
  14. return this.sd.deleteStudent(name);
  15. }
  16. public int update(String name)
  17. {
  18. return this.sd.updateStudent(name);
  19. }
  20. public Student find(String name)
  21. {
  22. return this.sd.findStudent(name);
  23. }
  24. public Set<Student> findAll()
  25. {
  26. return this.sd.findAll();
  27. }
  28. }

7.定义一个测试类,相当于 (表现层)

Client.java

  1. package com.myjdbc.test;
  2. import java.util.HashSet;
  3. import java.util.Iterator;
  4. import java.util.Set;
  5. import com.myjdbc.bean.Student;
  6. import com.myjdbc.service.StudentService;
  7. public class Client {
  8. public static void main(String[] args)
  9. {
  10. Student stu = new Student();
  11. Set<Student> set = new HashSet<Student>();
  12. //     stu.setStuName("zhangsan");
  13. //     stu.setStuAge(20);
  14. //     stu.setStuTel("18779157911");
  15. //     stu.setStuAddress("china");
  16. //     stu.setGroupId(1);
  17. StudentService ss = new StudentService();
  18. //System.out.println(ss.add(stu));
  19. //System.out.println(ss.delete("aa"));
  20. //System.out.println(ss.update("bb"));
  21. //stu = ss.find("cc");
  22. //System.out.println(stu.getStuName() +" " +stu.getStuAge()+" "+stu.getStuTel()+" "+stu.getStuAddress()+" "+stu.getGroupId());
  23. set = ss.findAll() ;
  24. Iterator<Student> iterator = set.iterator();
  25. while(iterator.hasNext())
  26. {
  27. Student student =  (Student)iterator.next() ;
  28. System.out.println(student.getStuName() +" " +student.getStuAge()+" "+student.getStuTel()+" "+student.getStuAddress()+" "+student.getGroupId());
  29. }
  30. }
  31. }

最新文章

  1. pt-ioprofile
  2. CentOS7下安装和使用Xdebug
  3. weblogic启动失败:Could not obtain the localhost address 解决办法
  4. xheditor编辑器的使用
  5. 第一课 python的几种环境配置
  6. Azure 上为Liunx VM 挂载File类型的存储。
  7. 洛谷P1251 餐巾(网络流)
  8. mongodb 简单部署方案及实例
  9. EasyUI篇の日期控件
  10. Linux入门基础教程
  11. 实战ajax
  12. Cocos2dx中Plugin-X 在android下的整合
  13. Zepto.js入门介绍
  14. acm入门搜索-水池数目
  15. 模型加速[tensorflow&amp;tensorrt]
  16. axios 在Vue全局引入的方法
  17. iOS开发:一个无限滚动自动播放图片的Demo(Swift语言编码)
  18. 019-JQuery(Ajax异步请求)
  19. CNN卷积层:ReLU函数
  20. python3操作数据库 借助pycharm快速连接并操作mysql数据库

热门文章

  1. [BJOI2011]禁忌 --- AC自动机 + 矩阵优化 + 期望
  2. WC2018伪题解
  3. POJ 3974 Palindrome 字符串 Manacher算法
  4. SCOJ 4429: frog&#39;s dice 最大流
  5. Unity UGUI之Image
  6. Unity 的一些特性
  7. Map中keySet和entrySet的区别
  8. Spring JdbcTemplate查询实例
  9. HDU 2896 病毒侵袭 【AC自动机】
  10. linux /proc/pid进程信息说明