java连接mysql封装代码_JDBC连接数据库方法的封装,以及查询数据方法的封装

(在上一篇文章中,我们详细的介绍了连接数据库的方法,以及eclipse操作数据库信息的相关方法,在这里我们将主要讲封装。)

主要内容:

一般的连接数据库测试

把连接数据库的方法封装成一个类和测试

一个简单的插入表实例

查询数据实例

封装查询的数据库的信息

封装信息后的查询数据库

一.一般的数据库连接测试

1 public classTestConnection1 {2 public static void main(String[] args) throwsException {3 Class.forName("com.mysql.jdbc.Driver");4 String url="jdbc:mysql://localhost:3306/test?"//数据库url

5 + "useUnicode=true&characterEncoding=UTF8";//防止乱码

6 String user="h4";7 String pass="111";8 Connection conn=DriverManager.getConnection(url, user, pass);9

10 System.out.println(conn+",成功连接数据库");11 conn.close();12 }13 }

二.我们不可能每写一个处理信息功能就写一次连接,这样太麻烦,那么为了方便以后的应用,我们通常把数据库连接封装起来。

具体实现步骤如下:

1.定义变量:

private static String DRIVER_CLASS;

private static String URL;

private static String USERRNAME;

private static String PASSWORD;

2.在你建的eclipse根目录下新建一个File文件Properties;

文件内容为你定义的变量所指向的对象:

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=UTF8

user=h4

pass=111

3.构建一个Properties对象:Properties p=new Properties();

4. java.io下的类FileInputStream的方法;FileInputStream(String name) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

来获取这个文件里面的资料:FileInputStream fis=new FileInputStream("db.properties");

5. 用3构建的变量p来下载资料:p.load(fis);

6.利用getProperty();获取参数:

DRIVER_CLASS=p.getProperty("driver");

URL=p.getProperty("url");

USERRNAME=p.getProperty("user");

PASSWORD=p.getProperty("pass");

7.写一个连接数据库的方法getConection();

8.写一个关闭数据库的方法close(Connection conn);

写好后代码如下:

1 public classjdbcutil {2 private staticString DRIVER_CLASS;3 private staticString URL;4 private staticString USERRNAME;5 private staticString PASSWORD;6 private static Properties p=newProperties();7 static{8 try{9 FileInputStream fis=new FileInputStream("db.properties");10 p.load(fis);11 DRIVER_CLASS=p.getProperty("driver");12 URL=p.getProperty("url");13 USERRNAME=p.getProperty("user");14 PASSWORD=p.getProperty("pass");15 Class.forName(DRIVER_CLASS);16 fis.close();17 } catch(IOException e) {18 e.printStackTrace();19 } catch(ClassNotFoundException e) {20 e.printStackTrace();21 }22 }23 public staticConnection getConection(){24 Connection conn=null;25 try{26 conn=DriverManager.getConnection(URL, USERRNAME, PASSWORD);27 }28 catch(Exception e) {29 e.printStackTrace();30 }31 returnconn;32 }33 public static voidclose(Connection conn) {34 try{35 if (conn != null)36 conn.close();37 } catch(Exception e) {38 e.printStackTrace();39 }40 }41

42 }

那么封装好之后,我们来写一个测试类,测试连接

1 public classTestConnection2 {2

3 public static void main(String[] args) throwsException {4 Connection conn=jdbcutil.getConection();//利用封装好的类名来调用连接方法便可

5 System.out.println(conn+",成功连接数据库");6 jdbcutil.close( conn);//同样利用类名调用关闭方法即可

7 }8 }

三.连接成功,我们写一个简单的向数据库插入表的实例。

1 public classTestDDl {2

3 public static voidmain(String[] args) {4 Connection conn=null;5 Statement stmt=null;6 conn=jdbcutil.getConection();//连接数据库

7 String createTableSql= " create table user_test1( "+//记住引号和单词间一定要有空格

8 " id int, "+

9 " name varchar(32) , "+

10 " password varchar(32) , "+

11 " birthday date "+

12 " ) ";13 try{14 stmt=conn.createStatement();15 stmt.execute(createTableSql);16 } catch(SQLException e) {17 e.printStackTrace();18 }19 jdbcutil.close(null, stmt, conn);//关闭数据库

20 }21 }

四.我们在写一个查询数据库数据的实例。(有三种方法)

1 public classTestDQL {2 public static voidmain(String[] args){3 Connection conn=null;//定义为空值

4 Statement stmt=null;5 ResultSet rs=null;6 String sql="select * from employees";//sql语句

7 conn=jdbcutil.getConection();8 try{9 stmt=conn.createStatement();//创建一个Statement语句对象

10 rs=stmt.executeQuery(sql);//执行sql语句

11 while(rs.next()){12 System.out.print(rs.getInt(1)+",");13 System.out.print(rs.getString(2)+",");//直接使用参数14 System.out.print(rs.getString(3)+",");15 System.out.print(rs.getString(4)+",");16 System.out.println(rs.getString(5));17 }18 } catch(SQLException e) {19 e.printStackTrace();20 }finally{21 jdbcutil.close(rs,stmt,conn);//关闭数据库

22 }23 }24 }

//第二种方法如下:

1 public classTestDQl2 {2

3 public static voidmain(String[] args) {4 Connection conn=null;5 Statement stmt=null;6 ResultSet rs=null;7 String sql="select * from employees";8 conn=jdbcutil.getConection();9 try{10 stmt=conn.createStatement();11 rs=stmt.executeQuery(sql);12 while(rs.next()){13 System.out.print(rs.getInt("userid")+",");//里面直接写要查找的内容名称

14 System.out.print(rs.getString("employee_id")+",");15 System.out.print(rs.getString("last_name")+",");16 System.out.print(rs.getString("salary")+",");17 System.out.println(rs.getString("department_id"));18 }19 } catch(SQLException e) {20 e.printStackTrace();21 }finally{22 jdbcutil.close(rs,stmt,conn);23 }24 }25 }

1 //第三种方法如下:

2 public classTestDQL3 {3 public static voidmain(String[] args) {4 Connection conn=null;5 Statement stmt=null;6 ResultSet rs=null;7 String sql="select * from employees";8 conn=jdbcutil.getConection();9 try{10 stmt=conn.createStatement();11 rs=stmt.executeQuery(sql);12 while(rs.next()){13 int index=1;14 System.out.print(rs.getInt(index++)+",");15 System.out.print(rs.getString(index++)+",");16 System.out.print(rs.getString(index++)+",");17 System.out.print(rs.getString(index++)+",");18 System.out.println(rs.getString(index++));19 }20 } catch(SQLException e) {21 e.printStackTrace();22 }finally{23 jdbcutil.close(rs,stmt,conn);24 }25 }26 }

五.在四里面我们写了查询员工资料的信息,但是有的时候我们要保存起来方便之后更好的查找,那怎么办呢?没错,封装。

1 public class employees implementsSerializable {2 privateInteger userid;3 privateString employee_id;4 privateString last_name;5 privateString salary;6 privateString department_id;7

8 publicemployees() {9 super();10 }11

12 publicemployees(String employee_id, String last_name, String salary, String department_id) {13 super();14 this.employee_id =employee_id;15 this.last_name =last_name;16 this.salary =salary;17 this.department_id =department_id;18 }19

20 @Override21 publicString toString() {22 return "employees [userid=" + userid + ", employee_id=" + employee_id + ", last_name=" +last_name23 + ", salary=" + salary + ", department_id=" + department_id + "]";24 }25

26 publicInteger getUserid() {27 returnuserid;28 }29

30 public voidsetUserid(Integer userid) {31 this.userid =userid;32 }33

34 publicString getEmployee_id() {35 returnemployee_id;36 }37

38 public voidsetEmployee_id(String employee_id) {39 this.employee_id =employee_id;40 }41

42 publicString getLast_name() {43 returnlast_name;44 }45

46 public voidsetLast_name(String last_name) {47 this.last_name =last_name;48 }49

50 publicString getSalary() {51 returnsalary;52 }53

54 public voidsetSalary(String salary) {55 this.salary =salary;56 }57

58 publicString getDepartment_id() {59 returndepartment_id;60 }61

62 public voidsetDepartment_id(String department_id) {63 this.department_id =department_id;64 }65 }

六.封装好后的查询和上面没封装之前有点变化。

1 public classTestDQL4 {2 public static voidmain(String[] args) {3 Connection conn=null;4 Statement stmt=null;5 ResultSet rs=null;6 List emps=new ArrayList<>();//构造集合对象

7

8 String sql="select * from employees";9

10 conn=jdbcutil.getConection();//获取数据库连接

11

12 try{13 stmt=conn.createStatement();14 rs=stmt.executeQuery(sql);15 while(rs.next()){//遍历结果集16 int index=1;17 employees emp=new employees();//构造员工类对象

18 emp.setUserid(rs.getInt(index++));//获取值

19 emp.setEmployee_id(rs.getString(index++));20 emp.setLast_name(rs.getString(index++));21 emp.setSalary(rs.getString(index++));22 emp.setDepartment_id(rs.getString(index++));23 emps.add(emp);//放到集合中去

24 }25 } catch(SQLException e) {26 e.printStackTrace();27 }finally{28 jdbcutil.close(rs,stmt,conn);//关闭连接

29 }30 for(employees emp:emps){//遍历

31 System.out.println(emp);32 }33 }34 }

其实我们可以继续封装,把遍历结果集给封装起来。

1 public classTestDQL5 {2

3 public static voidmain(String[] args) {4 Connection conn=null;5 Statement stmt=null;6 ResultSet rs=null;7 List emps=new ArrayList<>();8

9 String sql="select * from employees";10

11 conn=jdbcutil.getConection();12

13 try{14 stmt=conn.createStatement();15 rs=stmt.executeQuery(sql);16 emps=resultSetToEmployees(rs);17 } catch(SQLException e) {18 e.printStackTrace();19 }finally{20 jdbcutil.close(rs,stmt,conn);21 }22 for(employees emp:emps){23 System.out.println(emp);24 }25 }26 public static ListresultSetToEmployees(ResultSet rs){27 List emps=new ArrayList<>();28 try{29 while(rs.next()){30 int index=1;31 employees emp=newemployees();32 emp.setUserid(rs.getInt(index++));33 emp.setEmployee_id(rs.getString(index++));34 emp.setLast_name(rs.getString(index++));35 emp.setSalary(rs.getString(index++));36 emp.setDepartment_id(rs.getString(index++));37 emps.add(emp);38 }39 } catch(SQLException e) {40 e.printStackTrace();41 }42

43 returnemps;44 }45 }

如果是一个人查询信息呢?还可以这样封装。

1 public classTestDQL6 {2 public static voidmain(String[] args) {3 Connection conn=null;4 Statement stmt=null;5 ResultSet rs=null;6 List emps=new ArrayList<>();7

8 String sql="select * from employees";9

10 conn=jdbcutil.getConection();11

12 try{13 stmt=conn.createStatement();14 rs=stmt.executeQuery(sql);15 while(rs.next()){16 employees emp=resultSetToEmployee(rs);17 emps.add(emp);18 }19 } catch(SQLException e) {20 e.printStackTrace();21 }finally{22 jdbcutil.close(rs,stmt,conn);23 }24 for(employees emp:emps){25 System.out.println(emp);26 }27 }28 public staticemployees resultSetToEmployee(ResultSet rs){29 employees emp=null;30 try{31 int index=1;32 emp=newemployees();33 emp.setUserid(rs.getInt(index++));34 emp.setEmployee_id(rs.getString(index++));35 emp.setLast_name(rs.getString(index++));36 emp.setSalary(rs.getString(index++));37 emp.setDepartment_id(rs.getString(index++));38 } catch(SQLException e) {39 e.printStackTrace();40 }41 returnemp;42 }43 }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/503399.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql连接字符串加密配置文件_Asp.net2.0如何加密Web.config配置文件数据库连接字符串...

在asp.net2.0中,发布网站时,加密web.config,这样可以有效保证数据库用户和密码安全,其步骤如下:①添加密钥执行:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pc "hnlaw" -exp其中"hnlaw"为密钥名称②添加web.config节点在web.config的之…

Java编程和C语言哪个更好?

学编程用哪一个编程语言好?很多人刚开始接触编程的时候都不知道自己该学哪个好&#xff0c;软件开发编程语言多达600余种&#xff0c;每种都有各自的特点和应用领域。目前&#xff0c;热门编程语言无外乎Java、C、C了&#xff0c;实际上&#xff0c;Java确实是从C语言和C语言继…

bugzilla dbd-mysql_别人写的关于在Windows下安装BugZilla的说明,不错,值得借鉴

Bugzilla Windows安装红宝书一直寻找合适的Bug Tracking System&#xff0c;网上找了很久&#xff0c;commercial的太贵&#xff0c;还有licence限制&#xff0c;远远超出我等贫民的承受范围。也曾考虑干脆自己写一个算了&#xff0c;但终究未能如愿。对Bugzilla倒是早有所闻&a…

Java程序员常犯的几类错误

1.忽视异常 相信很多小伙伴在编程的过程中经常对异常置之不理。针对初学者和有经验的 Java 程序员&#xff0c;最佳实践仍是处理它们。异常抛出通常是带有目的性的&#xff0c;因此在大多数情况下需要记录引起异常的事件。不要小看这件事&#xff0c;如果必要的话&#xff0c;…

jdk1.8 mysql_Centos 7配置JDK1.8+MySQL5.7+Tomcat 8 开发环境

工具腾讯云服务器(可通过公网ip访问)Xshell 6Xftp 61、Xshell 6 连接云服务器打开xshell很简单&#xff0c;直接上图配置好之后连接云服务器&#xff0c;之后就可以对云服务器进行操作了。2、配置JDK 1.8a、下载JDK1.8如果直接在云服务器的命令行中使用wget http://download.or…

做为一名java高级程序员,需要了解哪些岗位?

一、Java高级程序员 要想成为JAVA&#xff08;高级&#xff09;程序员也称Java高级工程师&#xff0c;肯定要学习JAVA。一般的程序员或许只需知道一些JAVA的语法结构就可以应付了。但要成为JAVA高级程序员&#xff0c;您要对JAVA做比较深入的研究。您应该多研究一下JDBC、IO包…

mysql 复制延迟诊断_新特性解读 | MySQL 8 复制延迟观测新方式,更全面更精准

转载自公众号&#xff1a;玩转MySQL&#xff0c;作者&#xff1a;洪斌一直以来 MySQL 复制延迟观测是不完善的&#xff0c;既无法观测到真实的主从延迟&#xff0c;也无法支持复杂的复制拓扑环境&#xff0c;常用的 second_behind_master 指标更多是判断是否存在回放延迟&#…

Java 程序员必读的五本书籍

如果你是一名程序员&#xff0c;想知道如何提高你对Java的了解或者成为更好的Java开发人员。在本文中&#xff0c;我将分享一些最好的Java书籍。这些书经受住了时间的考验&#xff0c;随着岁月的流逝变得越来越重要。不管你是学生还是职业者&#xff0c;你总有很多东西要学&…

使用sqlserver连接mysql服务_Sqlserver创建连接MySql的链接服务器

第一步&#xff1a;在MySql服务器上安装与系统对应的 MySql-Connector-ODBC安装过程中可能会报 缺失 msvcr100.dll的错误&#xff0c;这需要你根据系统到网上下载对应的这个dll文件。(当初遇到这个问题的时候&#xff0c;在网上试了很多的这种文件 最后才找到一个合适自己的)第…

什么人适合学习Java编程?编程好学吗?

什么人适合学习Java编程&#xff1f;编程好学吗&#xff1f;首先自己做个自我评估&#xff0c;包括能力、兴趣、逻辑思维、性格特点等等&#xff0c;结合这些特质判断自己是否适合学习Java。评估自己时&#xff0c;要尽量客观&#xff0c;追随内心&#xff0c;切勿轻易抬高或者…

not support mysql_MYSQL(解决方法):Client does not support authentication

mysql4.1以上版本连接时出现Client does not support authentication protocol问题解决办法shell> mysqlClient does not support authentication protocol requestedby server; consider upgrading MySQL client官方的说法是MySQL 4.1 and up uses an authentication proto…

mysql分布式如何实现原理_分布式通讯协议实现原理

分为两个阶段&#xff1a;投票表决阶段和提交阶段。事务参与者完成系统相关业务成功后&#xff0c;通知协调者状态&#xff0c;当所有的事务参与者业务状态都成功后&#xff0c;协调者才发出提交指令&#xff0c;参与者提交或者取消事务一协调者 二事务的参与者(一般有多个事务…

大神程序员都懂英文翻译,而你却因英语不行遭拒?

程序员中很多人都是在外企里面工作的。这样的话就会涉及到&#xff0c;跟外籍同事的沟通和协作。上下级之间的汇报工作。虽然我们的主要工作是开发软件。是技术类工作。跟计算机打交道比较多&#xff0c;但是沟通对技术来说&#xff0c;还是非常重要的。跟外籍同事沟通&#xf…

android找不到符号_快速搭建Android开发环境——Android Studio(附ADB找不到设备)...

由于毕设大概率最终要使用Android来实现&#xff0c;所以现在要开始学习一些Android开发基础了。学习一门技术&#xff0c;最先要解决的问题就是开发环境的问题。就如同两年前学java那样&#xff0c;在windows下配置环境总是一件不那么令人开心的事。Android也是一样&#xff0…

Java环境的正确配置你会了吗?

在很多新手入门学习Java的小伙伴都会面临到Java环境的配置&#xff0c;今天小编带大家来配置Java的环境配置&#xff0c;首先到官网下载Jdk:https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 安装的话傻瓜式安装只需要下一步就可以&…

让初学者不迷茫的Java学习方法有很多?

相信各位小伙伴在学习过程中多少会遇到一些迷茫&#xff0c;学习是一个循序渐进的过程&#xff0c;最初的最基本的知识没有掌握&#xff0c;直接学习在这之上的更高层次的知识&#xff0c;最大的问题就是只能做到知其然&#xff0c;而不能做到知其所以然了。在之前小编也只是一…

mysql execute指令_MYSQL简单命令

常用 mysql 操作指令&#xff1a;连接&#xff1a;mysql -u用户名 -p密码退出&#xff1a;mysql>exit;建数据库&#xff1a;mysql>create database ???;显示数据库&#xff1a;mysql>show databases;//(-s)删除数据库&#xff1a;mysql>drop database ???;连…

mysql日期纬度表_mysql中生成时间维度表

mysql中生成时间维度表利用mysql常用日期函数生成时间维度表&#xff0c;效率最高&#xff0c;最简单&#xff0c;无需其他的一些工具支持。生成结果示例如下图&#xff1a;# time spanSET d0 "2012-01-01";SET d1 "2012-12-31";SET date date_sub(d0, …

Java程序员高效开发必备工具,其中有你的最爱吗?

对于Java编程开发&#xff0c;有两种不同的观点&#xff1a;一种认为Java是最简单功能最强大的编程语言之一&#xff0c;另一种则表示这种编程语言既难用又复杂。&#xff0c;每个工具都有其优点&#xff0c;学习这些具有可以帮助开发者改善代码质量&#xff0c;从而成为一个更…

mysql怎么实现生日字段前一个小时提醒_MySql学习笔记(二) 索引的设计和使用...

作为开发人员&#xff0c;数据库的索引是我们再熟悉不过的了。那么实话真的会了吗&#xff0c;在项目开发中随便定义一个int、varchar后边跟个primary key或者加个index就好了么&#xff1f;考虑到这些咋还真的需要看看专业的人都是怎么做的。在mysql中索引是提升性能的常用工具…