搭环境所需软件:
apache-tomcat-5.5.27.zip
eclipse-SDK-3.2.2-win32.zip
MyEclipseEnterpriseWorkbenchInstaller_5.0.1GA_E3.2.exe
jdk-1_5_0_04-windows-i586-p.exe
mysql-connector-java-5.1.6.zip
mysql-5.0.18-win32
MySQL-Front_Setup.exe
配置和连接MySQL数据库
将mysql-connector-java-5.1.6.zip中的mysql-connector-java-5.1.6-bin.jar放到apache-tomcat-5.5.27\webapps\项目名\WEB-INF\lib下面。
package conn;
import java.sql.*;
public class conn {//Connection对象代表数据库连接,也就是在已经加载的Driver和数据库之间建立连接。必须创建一个Connection的实例,其中包括你的数据库信息。
Connection con;
public conn() {}
public Connection getConn(){
String url="jdbc:mysql://localhost:3306/数据库名";
try
{ //Drive loading 装载特定厂商提供的数据库驱动程序,JDBC Driver.
Class.forName("com.mysql.jdbc.Driver").newInstance();
//create connection:DriverManager激发getConnection()方法时,DriverManager类首先从它已加载的驱动程序中找到一个可以接受该数据库URL的驱动程序,然后请求该驱动程序使用相关的数据库URL链接到数据库中。
con=DriverManager.getConnection(url,"root","123");
return con;
}catch(ClassNotFoundException e)
{
System.out.println("Error:Drive loading");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void close()
{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet executeSql(String sqlstr) //ResultSet类型的executeSql方法
{
Statement stmt;
try
{
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sqlstr);
return rs;
}
catch(SQLException e)
{
System.out.print("ResultSet is wrong");
}
return null;
}
public void insertSql(String sqlstr) //将数据插入表格方法
{
Statement stmt;
try
{
stmt=con.createStatement();
stmt.executeUpdate(sqlstr);
}
catch(SQLException e)
{
System.out.print("Error:insertSql");
}
}
public void updateSql(String sqlstr) //更新表格方法
{
Statement stmt;
try
{
stmt=con.createStatement();
stmt.executeUpdate(sqlstr);
}
catch(SQLException e)
{
System.out.print("Error:insertSql");
}
}
public void delSql(String sqlstr)//删除表中记录方法
{
Statement stmt;
try
{
stmt=con.createStatement();
stmt.executeUpdate(sqlstr);
}
catch(SQLException e)
{
System.out.print("Error:delSql");
}
}
public void deleteSql(String sqlstr)//删除表中记录方法(同上)
{
Statement stmt;
try
{
stmt=con.createStatement();
stmt.executeUpdate(sqlstr);
}
catch(SQLException e)
{
System.out.print("Error:deleteSql");
}
}
public ResultSet fenyeexecuteSql(String sqlstr) //数据分页方法
{
Statement stmt;
try
{
stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs=stmt.executeQuery(sqlstr);
return rs;
}
catch(SQLException e)
{
System.out.print("获取数据集时出现错误");
}
return null;
}
}
在jsp页面或者servlet中要连接数据库,加入以下语句:
import conn.conn;
conn con = new conn();
con.getConn();
ResultSet rs = con.executeSql("select语句");
con.insertSql("insert语句");
con.updateSql("update语句");
con.deleteSql("delete语句");