赞
踩
首先写一个实体类
- package pojo;
-
- public class U {
- private String username;
- private String password;
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- @Override
- public String toString() {
- return "U{" +
- "username='" + username + '\'' +
- ", password='" + password + '\'' +
- '}';
- }
- }

这段代码是用来对实体类进行数据的封装
下面在写一个数据库的连接类,包括了查询和更新的封装代码
- package utils;
-
-
-
- import java.io.IOException;
- import java.io.InputStream;
- import java.lang.reflect.Field;
- import java.sql.*;
- import java.util.HashMap;
- import java.util.Map;
-
-
- public class connectionUtils {
- private static String username ="admin";
- private static String password ="DEFdef123!";
- private static String url="jdbc:mysql://localhost:3306/db1";
- private static String driver="com.mysql.jdbc.Driver";
- private static Connection conn ;
- private static Statement ts ;
- private static ResultSet rs;
- static{
- try {
- Class.forName(driver);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
-
-
- //封装连接
- public static Connection getConnection() throws SQLException {
- return DriverManager.getConnection(url,username,password);
- }
- //封装流的关闭
- public static void jdbcClose(ResultSet rs,Statement ts,Connection conn) throws SQLException {
- try{
- rs.close();
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- finally {
- if(rs!=null){
- rs=null;
- }
- }
- ts.close();
- if(ts!=null){
- ts=null;
- }
- conn.close();
- if(conn!=null){
- conn=null;
- }
- }
- //更新封装
- public static int update(String sql,Object...argv) throws SQLException {
- //定义一个变量Prepared

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。