jsp mysql JavaBean
==============
SETUP mysql db
==============
JavaBean
package com.myapp.struts;
/**
*
* @author webice
*/
import java.sql.*; //导入数据库操作的类
public class DBConnMySql //构造方法,初始化
{
private Connection conn; //连接对象
private Statement stmt; //语句对象
private ResultSet rs; //结果集对象
private String MySqldriver;//MYSQL Server驱动程序字符串
private String MySqlURL; //MYSQL Server连接字符串
//********************************
// *用 org.gjt.mm.mysql.Driver 驱动
// * 该方法取得连接所需各种参数,组成连接字符串,然后再建立连接
// * server;dbname,user,pass,port 分别表示MYSQL 服务器的地址,
// * 数据库,用户名,密码,端口
// **********************************/
public Connection getConnToMySql(String server,String dbname,String user,String pass,String port){
//MYSQl驱动程序
MySqldriver = "org.gjt.mm.mysql.Driver";
MySqlURL = "jdbc:mysql://"; //连接字符串一部分
try{
//完整的连接字符串
MySqlURL =MySqlURL+server+":"+port+"/"+dbname+"?user="+user+"&password="+pass+"&useUnicode=true&characterEncoding=GB2312";
Class.forName(MySqldriver);
conn = DriverManager.getConnection(MySqlURL);
}catch(Exception e){
System.out.println("操作数据库出错,请仔细检查");
//System.err.println(e.getMessage());
}
return conn;
}
//关闭数据库连接
public void close()
{
try{
//rs.close();
//stmt.close();
conn.close();
}catch(SQLException sqlexception){
sqlexception.printStackTrace();
}
}
}
=======================
JSP page useBean
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" %>
<jsp:useBean id="DBConn" scope="page" class="com.myapp.struts.DBConnMySql"/><%
//以下几项请自行修改
String server="localhost"; //MYSQL 服务器的地址
String dbname="mysql_test"; //MYSQL 数据库的名字
String user="root"; //MYSQL 数据库的登录用户名
String pass="19740415"; //MYSQL 数据库的登录密码
String port="3306"; //SQL Server 服务器的端口号,默认为1433
Connection conn=DBConn.getConnToMySql(server, dbname, user, pass, port);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String sql="select * from users";
String sql1="insert into users(name, pwd) values('ag', 'ag')";
stmt.executeUpdate(sql1);
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
out.print("用户名:");
out.print(rs.getString("name")+" 密码:");
out.println(rs.getString("pwd")+"<br>");
}
//rs.close();
//stmt.close();
//conn.close();
DBConn.close();
%>