您的位置:首页 > 编程语言 > Java开发

java连接MySql数据库!

2004-12-18 14:48 489 查看
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /> 

package com.roytel.rtccp.util;
 

import java.sql.*;
 

public class DBManager {
//用户名
  private String user = "";
//密码
  private String password = "";
//主机
  private String host = "";
//数据库名字
  private String database = "";
 

  /*
     private String url="jdbc:mysql://"+host+"/"+"useUnicode=true&characterEncoding=GB2312";
   */
  private String url ="";
  private Connection con = null;
 

  Statement stmt;
  /**
   * 根据主机、数据库名称、数据库用户名、数据库用户密码取得连接。
   * @param host String
   * @param database String
   * @param user String
   * @param password String
   */
  public DBManager(String host, String database, String user, String password) {
 

    this.host = host;
    this.database = database;
    this.user = user;
this.password = password;
//显示中文
    this.url = "jdbc:mysql://" + host + "/" + database +
        "?useUnicode=true&characterEncoding=GB2312";
 

    try {
      Class.forName("org.gjt.mm.mysql.Driver");
    }
    catch (ClassNotFoundException e) {
      System.err.println("class not found:" + e.getMessage());
    }
 

    try {
      con = DriverManager.getConnection(this.url, this.user, this.password);
//连接类型为ResultSet.TYPE_SCROLL_INSENSITIVE,                                 ResultSet.CONCUR_READ_ONLY
      stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                                 ResultSet.CONCUR_READ_ONLY);
    }
    catch (SQLException a) {
      System.err.println("sql exception:"
4000
+ a.getMessage());
    }
  }
/**
* 返回取得的连接
*/
  public Connection getCon() {
    return con;
  }
/**
* 执行一条简单的查询语句
* 返回取得的结果集
*/
  public ResultSet executeQuery(String sql) {
    ResultSet rs = null;
    try {
      rs = stmt.executeQuery(sql);
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
    return rs;
  }
/**
* 执行一条简单的更新语句
* 执行成功则返回true
*/
  public boolean executeUpdate(String sql) {
    boolean v = false;
    try {
      v = stmt.executeUpdate(sql) > 0 ? true : false;
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
    finally {
      return v;
    }
  }
 

}

能用的,你可以扩充,比如增加执行预编译语句的方法、执行存储过程的方法,也可以用连接池的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息