类型:转载 责任编辑:asp.net 日期:2007/05/23
热门软件下载:
如何连接MYSQL数据库,并取出库中数据!
给个简单点的吧!
谢谢!
我刚学JSP
请各位支持!
网友回答:
一般情况,都是交给BEAN来处理的
package bean;
import java.sql.*;
import java.io.*;
import javax.servlet.http.*;
public class Sql_data implements HttpSessionBindingListener
{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://127.0.0.1/webdb";
Connection conn=null;
ResultSet rs=null;
//构造函数
public Sql_data()
{
try
{
Class.forName(driver);
}
catch(java.lang.ClassNotFoundException e)
{
System.out.println("Sql_data():"+e.getMessage());
}
}
//执行插入数据操作。
public void executeInsert(String sql)
{
try
{
conn=DriverManager.getConnection(url,"","");
Statement stmt=conn.createStatement();
stmt.executeUpdate(sql);
}
catch(SQLException ex)
{
System.out.println("Sql_data.executeInsert:"+ex.getMessage());
}
}
//执行数据查询
public ResultSet executeQuery(String sql)
{
try
{
conn=DriverManager.getConnection(url,"","");
Statement stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
}
catch(SQLException ex)
{
System.out.println("Sql_data.executeQuery:"+ex.getMessage());
}
return rs;
}
//执行删除数据操作
public void executeDelete(String sql)
{
try
{
conn=DriverManager.getConnection(url,"","");
Statement stmt=conn.createStatement();
stmt.executeUpdate(sql);
}
catch(SQLException ex)
{
System.out.println("Sql_data.executeDelete:"+ex.getMessage());
}
}
//关闭数据库
public void close()
{
try
{
conn.close();
conn=null;
}
catch(SQLException e1)
{
System.out.println("Sql_data.close():"+e1.getMessage());
}
}
//当变量加入Session时,将自动执行此函数
public void valueBound(HttpSessionBindingEvent event){}
//当Session变量消失时,将自动执行此函数
public void valueUnbound(HttpSessionBindingEvent event)
{
if(conn!=null)
close();
}
}
这个是我曾经用过的,没有问题的了,可能不够完好,请各位指点!!
TOMCAT中有例子
<%Class.forName("org.gjt.mm.mysql.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://url/数据库名?user=root&password= &useUnicode=ture & characterEncoding=gb2312");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select *from 表名");
.......................
Class.forName("org.gjt.mm.mysql.Driver").newsInstance();
--〉Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String sql="select title,name * from message"; 此句多了个“*”号
String url ="jdbc:mysql://127.0.0.1/dbname?user=accounts&password=password&useUnicode=true&characterEncoding=8859_1"
此句后面少了个分号
String url ="jdbc:mysql://127.0.0.1/dbname?user=accounts&password=password&useUnicode=true&characterEncoding=8859_1" ;
8859_1改为:gb2312
/**
* 处理jsp页面表单提交中文乱码问题
* @param strvalue
* @return
*/
public static String jsptoChinese(String strvalue) {
try {
if (strvalue == null) {
return null;
} else {
strvalue = new String(strvalue.getBytes("8859_1"));
return strvalue;
}
} catch (Exception ex) {
return null;
}
}
/**
* 处理数据库查询返回中文乱码问题
* @param strvalue
* @return
*/
public static String actiontoChinese(String strvalue) {
try {
if (strvalue == null) {
return null;
} else {
strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
return strvalue;
}
} catch (Exception e) {
return null;
}
}