欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java连接mysql底层封装详解

程序员文章站 2023-09-07 11:05:58
本文实例为大家分享了java连接mysql底层封装代码,供大家参考,具体内容如下 连接数据库 package com.dao.db; import java.sql....

本文实例为大家分享了java连接mysql底层封装代码,供大家参考,具体内容如下

连接数据库

package com.dao.db;

import java.sql.connection;
import java.sql.sqlexception;

/**
 * 数据库连接层mysql
 * @author administrator
 *
 */
public class dbconnection {
 
 
 /**
  * 连接数据库
  * @return
  */
 public static connection getdbconnection()
 {
  // 1. 注册驱动
  try {
   class.forname("com.mysql.jdbc.driver");
  } catch (classnotfoundexception e) {
   // todo auto-generated catch block
   e.printstacktrace();
  }
  // 获取数据库的连接
  try {
   connection conn = java.sql.drivermanager.getconnection("jdbc:mysql://localhost/mysql?useunicode=true&characterencoding=utf-8", "root", "root");
   return conn;
  } catch (sqlexception e1) {
   e1.printstacktrace();
  }
  return null;
 }
 
}

数据层封装

package com.dao.db;

import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.resultsetmetadata;
import java.sql.sqlexception;
import java.sql.types;
import java.util.arraylist;
import java.util.hashmap;

/**
 * mysql数据库底层封装
 * @author administrator
 *
 */
public class dbmanager {
 
 private preparedstatement pstmt;
 private connection conn;
 private resultset rs;
 

 /**
  * 打开数据库
  */
 public dbmanager() {
  conn = dbconnection.getdbconnection();
 }
 
 /**
  * 执行修改添加操作
  * @param coulmn
  * @param type
  * @param sql
  * @return
  * @throws sqlexception
  */
 public boolean updateoradd(string[] coulmn, int[] type, string sql) throws sqlexception
 {
  if(!setpstmtparam(coulmn, type, sql))
   return false;
  boolean flag = pstmt.executeupdate()>0?true:false;
  closedb();
  return flag;
 }
 /**
  * 获取查询结果集
  * @param coulmn
  * @param type
  * @param sql
  * @throws sqlexception
  */
 public datatable getresultdata(string[] coulmn, int[] type, string sql) throws sqlexception
 {
  datatable dt = new datatable();
  
  arraylist<hashmap<string, string>>list = new arraylist<hashmap<string, string>>();
  
  if(!setpstmtparam(coulmn, type, sql))
   return null;
  rs = pstmt.executequery();
  resultsetmetadata rsmd = rs.getmetadata();//取数据库的列名 
  int numberofcolumns = rsmd.getcolumncount();
  while(rs.next())
  {
   hashmap<string, string> rstree = new hashmap<string, string>(); 
   for(int r=1;r<numberofcolumns+1;r++)
    {
    rstree.put(rsmd.getcolumnname(r),rs.getobject(r).tostring());
    }
   list.add(rstree);
  }
  closedb();
  dt.setdatatable(list);
  return dt;
 }
 
 /**
  * 参数设置
  * @param coulmn
  * @param type
  * @throws sqlexception 
  * @throws numberformatexception 
  */
 private boolean setpstmtparam(string[] coulmn, int[] type, string sql) throws numberformatexception, sqlexception
 {
  if(sql== null) return false;
  pstmt = conn.preparestatement(sql);
  if(coulmn != null && type != null && coulmn.length !=0 && type.length !=0 )
  {  
   for (int i = 0; i<type.length; i++) {
    switch (type[i]) {
    case types.integer:
     pstmt.setint(i+1, integer.parseint(coulmn[i]));
     break;
    case types.boolean:
     pstmt.setboolean(i+1, boolean.parseboolean(coulmn[i]));
     break;
    case types.char:
     pstmt.setstring(i+1, coulmn[i]);
     break;
    case types.double:
     pstmt.setdouble(i+1, double.parsedouble(coulmn[i]));
     break;
    case types.float:
     pstmt.setfloat(i+1, float.parsefloat(coulmn[i]));
     break;
    default:
     break;
    }
   }
  }
  return true;
 }
 
 /**
  * 关闭数据库
  * @throws sqlexception
  */
 private void closedb() throws sqlexception
 {
  if(rs != null)
  {
   rs.close();
  }
  if(pstmt != null)
  {
   pstmt.close();
  }
  if(conn != null)
  {
   conn.close();
  }
  
 }
}

数据集封装

package com.dao.db;

import java.util.arraylist;
import java.util.hashmap;
import java.util.iterator;
import java.util.map;
import java.util.set;

/**
 * 数据集封装
 * @author administrator
 *
 */
public class datatable {
 
 public string[] column;//列字段
 public string[][] row; //行值
 public int rowcount = 0;//行数
 public int colcoun = 0;//列数
 
 
 public datatable() {
  super();
 }
 
 public datatable(string[] column, string[][] row, int rowcount, int colcoun) {
  super();
  this.column = column;
  this.row = row;
  this.rowcount = rowcount;
  this.colcoun = colcoun;
 }


 public void setdatatable(arraylist<hashmap<string, string>> list) {
  rowcount = list.size();
  colcoun = list.get(0).size();
  column = new string[colcoun];
  row = new string[rowcount][colcoun];
  for (int i = 0; i < rowcount; i++) {
   set<map.entry<string, string>> set = list.get(i).entryset();
   int j = 0;
   for (iterator<map.entry<string, string>> it = set.iterator(); it
     .hasnext();) {
    map.entry<string, string> entry = (map.entry<string, string>) it
      .next();
    row[i][j] = entry.getvalue();
    if (i == rowcount - 1) {
     column[j] = entry.getkey();
    }
    j++;
   }
  }
 }

 public string[] getcolumn() {
  return column;
 }

 public void setcolumn(string[] column) {
  this.column = column;
 }

 public string[][] getrow() {
  return row;
 }

 public void setrow(string[][] row) {
  this.row = row;
 }

 public int getrowcount() {
  return rowcount;
 }

 public void setrowcount(int rowcount) {
  this.rowcount = rowcount;
 }

 public int getcolcoun() {
  return colcoun;
 }

 public void setcolcoun(int colcoun) {
  this.colcoun = colcoun;
 }
 
 

}

测试demo

package com.bussiness.test;

import java.sql.sqlexception;
import java.sql.types;

import com.dao.db.dbmanager;
import com.dao.db.datatable;

public class testbusiness{
 
 static string searchsql = "select * from score";
 static string insertsql = "insert into score(name, age, score)values(?,?,?)";
 static string deletesql = "delete from score where id = ?";
 static string updatesql = "update score set name = ? where id = ?";
 
 public static void main(string[] args) {
  intsertdata();
  searchdata();
 }
 
 private static void intsertdata()
 { 
  dbmanager dm = new dbmanager();
  string[] coulmn = new string[]{"wyf2", "23", "89.5"};
  int[] type = new int[]{types.char, types.integer, types.double};
  
  try {
   boolean flag = dm.updateoradd(coulmn, type, insertsql);
   if(flag)
    system.out.println("插入成功");
  } catch (sqlexception e) {
   e.printstacktrace();
  }
 }
 private static void searchdata()
 { 
  dbmanager dm = new dbmanager();
  string[] coulmn = null;
  int[] type = null;
  
  try {
   datatable dt = dm.getresultdata(coulmn, type, searchsql);
   if(dt != null && dt.getrowcount()> 0){   
    for(int i = 0; i<dt.getrowcount(); i++)
    {
     for(int j = 0; j<dt.getcolcoun(); j++)
     system.out.printf(dt.getrow()[i][j]+"\t");
     system.out.println();
    }
   }
   else
    system.out.println("查询失败");
  } catch (sqlexception e) {
   e.printstacktrace();
  }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。