欢迎光临
我们一直在努力

java连接MySql数据库!-JSP教程,数据库相关

建站超值云服务器,限时71元/月

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;

}

}

}

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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » java连接MySql数据库!-JSP教程,数据库相关
分享到: 更多 (0)