注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

_

_

 
 
 

日志

 
 

Java连接MySql数据库  

2014-11-18 05:17:42|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
Java连接MySql数据库

2007-10-09 16:04:37|? 分类: 默认分类 |? 标签: |举报 |字号大中小 订阅

是我最近写的一个连接MySql数据库的一个例子,主要实现了插入,删除,更新,选择操作,用的环境是 j2sdk1.4.2_08,Eclipse3.1。以前我的同事用Python写了同样的类,非常的好用,支持了我们公司的大部分业务,现在我们慢慢改用Java了,所以我用Java重写了一遍。一方面在今后的业务中能够用到,另一方面熟悉一下Java。

下面我把在Eclipse3.1下怎样配置数据库连接信息简单说一下。

1.启动Eclipse3.1。

2.建立一个Java project就叫DbConnect 吧,再在该Project下建立一个新类也叫DbConnect 吧。

3.右击DbConnect.java文件点import,选择Archive file然后选择你的

mysql-connector-java-3.1.8-bin.jar文件,点Finish。你会看到有好些文件被加载进来,OK这就是连接MySql所需的驱动信息。如果到了这里你都成功的话那么恭喜你,你已经成功一半了!:)

4.接下来把我下面的代码copy到你的Java文件中,修改相关的数据库连接信息运行一下。OK?

我说一下那个mysql-connector-java-3.1.8-bin.jar文件,其实这就是一个MySql的驱动,各数据库厂商提供了不同的适用于JDBC的驱动使得在Java中连接数据库非常简单。这里我就不多说了,以后我会写篇专门介绍数据库驱动的文章。关于MySql的驱动还有更新版本的,你需要到MySql的网站上去下载,这个网上到处都是,我就不多说了。下面看程序,有些地方我写了详细的注释应该能看懂。这个类是非常有特色的,在每个方法的传人参数和返回值不变的情况下,希望高手能提出改进意见。多指教,谢谢!

/**

* 数据库连接、选择、更新、删除演示

*/

//import java.sql.*;

import java.sql.Connection;

import java.sql.Statement;

import java.sql.ResultSet;

import java.sql.DriverManager;

import java.util.*;

public class DbConnect

{

/////////////////////////////////////////----------->>>数据成员 and 构造函数

?????? private Connection dbconn;

?????? private Statement dbstate;

?????? private ResultSet dbresult;

?????? DbConnect()

?????? {

????????????? dbconn = null;

????????????? dbstate = null;

????????????? dbresult = null;

?????? }

/////////////////////////////////////////----------->>>类方法

?????? public void print(String str)//简化输出

?????? {

????????????? System.out.println(str);

?????? }//end print(...)

?????? /**

??????? * 连接MySql数据库

??????? * @param host

??????? * @param port

??????? * @param dbaName

??????? * @param usName

??????? * @param psw

??????? * @return bool值,连接成功返回真,失败返回假

??????? */

?????? public boolean dbConnection(String host, String port, String dbaName, String usName, String psw)

?????? {

????????????? String driverName = "com.mysql.jdbc.Driver";//"org.gjt.mm.mysql.Driver"两个驱动都可以用

????????????? String dbHost = host;//数据库的一些信息

????????????? String dbPort = port;

????????????? String dbName = dbaName;

????????????? String enCoding = "?useUnicode=true&characterEncoding=gb2312"; //解决MySql中文问题,要连续写不能空格

????????????? String userName = usName;

????????????? String Psw = psw;

????????????? String url = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName + enCoding;

????????????? try

????????????? {

???????????????????? Class.forName(driverName).newInstance();

???????????????????? dbconn = DriverManager.getConnection(url, userName, Psw);

???????????????????? //getConnection(url, userName, Psw)从给的driver中选择合适的去连接数据库

???????????????????? //return a connection to the URL

????????????? }catch(Exception e){

???????????????????? print("url = " + url); //发生错误时,将连接数据库信息打印出来

???????????????????? print("userName = " + userName);

???????????????????? print("Psw" + Psw);

???????????????????? print("Exception: " + e.getMessage());//得到出错信息

????????????? }

????????????? if (dbconn != null)//dbconn != null 表示连接数据库成功,由异常保证!?

???????????????????? return true;

????????????? else

???????????????????? return false;

?????? }// end boolean dbConnection(...)

?????? /**

??????? * 对数据库表进行选择操作!

??????? * @param tableName 数据库表名

??????? * @param fieles 字段名

??????? * @param selCondition 选择条件

??????? * @return 一个含有map的List(列表)

??????? */

?????? public ArrayList dbSelect(String tableName, ArrayList fields, String selCondition)

?????? {

????????????? ArrayList mapInList = new ArrayList();???

????????????? String selFields = "";

????????????? for (int i = 0; i<fields.size(); ++i)

???????????????????? selFields += fields.get(i) + ", ";

????????????? String selFieldsTem = selFields.substring(0, selFields.length() - 2);//根据String的索引提取子串

????????????? try{

???????????????????? dbstate = dbconn.createStatement();

???????????????????? String sql = "select " + selFieldsTem + " from " + tableName + selCondition;

???????????????????? print("sql = " + sql);

???????????????????? try{

??????????????????????????? dbresult = dbstate.executeQuery(sql);

???????????????????? }catch(Exception err){

??????????????????????????? print("Sql = " + sql);

??????????????????????????? print("Exception: " + err.getMessage());

???????????????????? }

???????????????????? while(dbresult.next()){

??????????????????????????? Map selResult = new HashMap();

??????????????????????????? selResult.put("message_type", dbresult.getString("message_type"));

??????????????????????????? selResult.put("message_content", dbresult.getString("message_content"));

??????????????????????????? mapInList.add(selResult);

???????????????????? }

????????????? }catch(Exception e){

???????????????????? print("Exception: " + e.getMessage());

????????????? }

????????????? return mapInList;

?????? }//end String dbSelect(...)

?????? /**

??????? * 对数据库表中的记录进行删除操作

??????? * @param tableName

??????? * @param condition

??????? * @return bool值,表示删除成功或者失败。

??????? */

?????? public boolean dbDelete(String tableName, String condition)

?????? {//-------->>>删除操作

????????????? boolean delResult = false;

????????????? String sql = "delete from " + tableName + " " + condition;

????????????? try{

???????????????????? dbstate.executeUpdate(sql);? //return int // int delRe = ??

???????????????????? delResult = true;

????????????? }catch(Exception e){

???????????????????? print ("sql = " + sql);

???????????????????? print ("Exception: " + e.getMessage());

????????????? }

????????????? if (delResult)

???????????????????? return true;

????????????? else

???????????????????? return false;

?????? }//end dbDelete(...)

?????? /**

??????? * 对数据库表中记录进行更新操作

??????? * @param tabName

??????? * @param reCount

??????? * @return bool值,成功返回true,失败返回false

??????? */

?????? public boolean dbUpdate(String tabName, HashMap reCount, String upCondition)

?????? {

????????????? boolean updateResult = false;

????????????? String Values = "";

????????????? Iterator keyValues = reCount.entrySet().iterator();

????????????? for(int i = 0; i<reCount.size(); ++i)

????????????? {

???????????????????? Map.Entry entry = (Map.Entry) keyValues.next();

???????????????????? Object key = entry.getKey();

???????????????????? Object value = entry.getValue();

???????????????????? Values += key + "=" + "'" + value + "'" + ", ";

????????????? }

????????????? String updateValues = Values.substring(0, Values.length() - 2);

????????????? String sql = "update " + tabName + " set " + updateValues + " " + upCondition;

????????????? try

????????????? {

???????????????????? dbstate.executeUpdate(sql);

???????????????????? updateResult = true;

????????????? }catch(Exception err){

???????????????????? print("sql = " + sql);

???????????????????? print("Exception: " + err.getMessage());

????????????? }

????????????? if (updateResult)

???????????????????? return true;

????????????? else

???????????????????? return false;

?????? }//end dbUpdate(...)

?????? /**

??????? * 对数据库表进行插入操作

??????? * @param tabName

??????? * @param hm

??????? * @return bool值,成功返回true,失败返回false

??????? */

?????? public boolean dbInsert(String tabName, HashMap values)

?????? {

????????????? String sql = "";

????????????? String insertFields = "", temFields = "";

????????????? String insertValues = "", temValues = "";

????????????? boolean insertResult = false;

????????????? Iterator keyValues = values.entrySet().iterator();

????????????? for(int i = 0; i<values.size(); ++i)

????????????? {

???????????????????? Map.Entry entry = (Map.Entry) keyValues.next();

???????????????????? Object key = entry.getKey();

???????????????????? Object value = entry.getValue();

???????????????????? temFields += key + ", ";

???????????????????? temValues += "'" + value + "'" + ", ";

????????????? }

????????????? insertFields = temFields.substring(0, temFields.length() - 2);

????????????? insertValues = temValues.substring(0, temValues.length() - 2);

????????????? sql += "insert into " + tabName + " (" + insertFields + ") values" + "(" + insertValues + ")";

????????????? try

????????????? {

???????????????????? dbstate.executeUpdate(sql);

???????????????????? insertResult = true;

????????????? }catch(Exception e){

???????????????????? print("Sql = " + sql);

???????????????????? print("Exception: " + e.getMessage());

????????????? }

????????????? if (insertResult)

???????????????????? return true;

????????????? else

???????????????????? return false;

?????? }//end dbInsert(...)

?????? /**

??????? * 断开数据库

??????? * @return bool值,成功返回true,失败返回false

??????? */

?????? public boolean dbClose()

?????? {

????????????? boolean closeResult = false;

????????????? try

????????????? {

???????????????????? dbconn.close();

???????????????????? closeResult = true;

????????????? }catch(Exception e){

???????????????????? print("Exception: " + e.getMessage());

????????????? }

????????????? if (closeResult)

???????????????????? return true;

????????????? else

???????????????????? return false;

?????? }//end dbClose()

/////////////////////////////////////////----------->>>入口主函数

?????? public static void main(String[] args)

?????? {

????????????? DbConnect dc = new DbConnect();

????????????? //连接数据库用到的一些参数.

????????????? String dbHost = "localhost";

????????????? String dbPort = "3306";

????????????? String dbName = "feast";

????????????? String dbuserName = "root";

????????????? String dbpsw = "";

????????????? boolean con = dc.dbConnection(dbHost, dbPort, dbName, dbuserName, dbpsw); //连接数据库

????????????? if (con)

????????????? {

???????????????????? ArrayList fields = new ArrayList();

???????????????????? fields.add("message_content");

???????????????????? fields.add("message_type");

???????????????????? Map lmap = new HashMap();

???????????????????? String selCondition = " where message_type = 1 limit 2";

???????????????????? ArrayList str = dc.dbSelect("feast", fields, selCondition); //--->>>选择记录

???????????????????? if (str.size() != 0){

??????????????????????????? dc.print("select OK!");

??????????????????????????? dc.print("str's size = " + str.size());

??????????????????????????? for(int i = 0; i<str.size(); ++i){

?????????????????????????????????? lmap = (HashMap)str.get(i);

?????????????????????????????????? dc.print("lmap = " + lmap);

??????????????????????????? }

???????????????????? }

????????????? }

????????????? else

???????????????????? dc.print("fail");

????????????? String tableName = "feast";

????????????? String condition = "where message_type = 5";

????????????? boolean del = dc.dbDelete(tableName, condition);//--->>>删除数据

????????????? if (

del)

???????????????????? dc.print("delete ok");

????????????? else

???????????????????? dc.print("delete error!");

????????????? HashMap m = new HashMap();

????????????? m.put("message_content", "ookkk");

????????????? m.put("message_number", "9");

????????????? String upCondition = "where message_type = 4";

????????????? boolean ur = dc.dbUpdate("feast", m, upCondition); //--->>>更新数据

????????????? if (

ur)

???????????????????? dc.print("update OK");

????????????? else

???????????????????? dc.print("update error!");

????????????? HashMap mm = new HashMap();

????????????? mm.put("message_number", "6");

????????????? mm.put("message_content", "insertefasdfas");

????????????? mm.put("message_type", "4");

????????????? boolean in = dc.dbInsert("feast", mm); //--->>>插入

????????????? if (in)

???????????????????? dc.print("insert OK");

????????????? else

???????????????????? dc.print("insert error!");

????????????? boolean close = dc.dbClose();//----->断开数据库

????????????? if (close)

???????????????????? dc.print("close OK");

????????????? else

???????????????????? dc.print("close fail");

?????? }//end main()

}//end class DbConnect

  评论这张
 
阅读(225)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017