/ 中存储网

Java程序连接MySQL数据库演示

2014-07-13 16:18:23 来源:中存储网

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:" + 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;

}

}

}

能用的,你可以扩充,比如增加执行预编译语句的方法、执行存储过程的方法,也可以用连接池的方法。