本章大部分例子采用的模式是JSP+JavaBean模式,即JSP页面调用bean来完成对数据库的操作,使用的数据库管理系统是SQL Server 2000。
1. SQL Server 2000数据库管理系统
SQL Server 2000是一个网络数据库,可以使远程的计算机访问它所管理的数据库。安装好SQL Server 2000后,需启动SQL Server 2000提供的数据库服务器,以便使远程的计算机访问它所管理的数据库。
如果您已经安装SQL Server 2000,可以如下操作启动SQL Server 2000提供的数据库服务器:单击“开始”→“程序”→“Microsoft SQL Server” →“服务器管理器”。
2. JDBC
JDBC(Java DataBase Connectivity)是Java运行平台的核心类库中的一部分,提供了访问数据库的API,它由一些Java类和接口组成。
JDBC操作不同的数据库仅仅是连接方式上的差异而已,使用JDBC的应用程序一旦和数据库建立连接,就可以使用JDBC提供的API操作数据库
使用JDBC进行如下操作:
与一个数据库建立连接。
向已连接的数据库发送SQL语句。
处理SQL语句返回的结果。
3. 数据库连接的常用方式
1.一种常见方式是建立起一个JDBC-ODBC桥接器:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2.另一种使用纯Java数据库驱动程序
加载SQLServer驱动程序代码如下:
Class.forName("com.microsoft.sqlserver. jdbc .SQLServerDriver");
4.查询操作
与数据库建立连接后,就可以使用JDBC提供的API和数据库交互信息,如查询、修改和更新数据库中的表等。
创建Statement对象
Statement sql=con.createStatement();
sql对象就可以调用相应的方法,实现对数据库中表的查询和修改,并将查询结果存放在一个ResultSet类声明的对象中
ResultSet rs=sql.executeQuery("SELECT * FROM score");
5. 更新、添加与删除操作
Statement对象调用方法:
public int executeUpdate(String sqlStatement);
通过参数sqlStatement指定的方式实现对数据库表中记录的更新、添加和删除操作.
6.分页显示记录
用户使用分页方式显示ResultSet对象中的数据,就必须始终保持和数据库的连接,直到用户将ResultSet对象中的数据查看完毕。我们知道,每种数据库在同一时刻都有允许的最大连接数目,因此当多个用户同时分页读取数据库表的记录时,应当避免长时间占用数据库的连接资源。
CachedRowSetImpl对象可以保存ResultSet对象中的数据,而且CachedRowSetImpl对象不依赖Connnection 对象,这意味着一旦把ResultSet对象中的数据保存到CachedRowSetImpl对象中后,就可以关闭和数据库的连接。
假设CachedRowSetImpl对象中有m行记录,准备每页显示n行,那么,总页数的计算公式是:
如果m除以n的余数大于0,总页数等于m除以n的商加1;
如果m除以n的余数等于0,总页数等于m除以n的商。
即总页数=(m%n)==0?(m/n):(m/n+1);
如果准备显示第p页的内容,应当把CachedRowSetImpl对象中的游标移动到第(p-1)*n+1 行记录处。
7.常见数据库连接
(1)连接Oracle数据库
加载驱动程序
Class.forName("oracle.jdbc.driver.OracleDriver");
建立连接
Connection conn=DriverManager.getConnection( "jdbc:oracle:thin:
@主机host:端口号:数据库名“, ”用户名“, ”密码“);
(2)连接MySql数据库
加载MySql驱动程序:
try{ Class.forName("com.mysql.jdbc.Driver")
}
catch(Exception e){ }
建立连接
try{ String uri= “jdbc:mysql://localhost/数据库名";
String user=“用户名";
String password=“密码";
con=DriverManager.getConnection(uri,user,password);
}
catch(SQLException e) { }
8.使用连接池
连接池的思想是:Tomcat服务器可以事先预备好若干个连接对象,将这些连接对象存放在一个称作连接池的容器中,通常由链表来担当这一角色。当某用户需要操作数据库时,只要从连接池中取出一个连接对象即可,当用户使用完该连接对象后,将该连接对象放回到连接池中。如果某用户需要操作数据库时,连接池中已没有连接对象可用,那么该用户就必须等待,直到连接池中有连接对象。
9.使用预处理语句
对于JDBC,如果使用Connection和某个数据库建立了连接对象con,那么 con就可以调用
prepareStatement(String sql)
方法对参数sql指定的SQL语句进行预编译处理,生成该数据库地层的内部命令,并将该命令封装在PreparedStatement对象中.
例子1
showByJdbcOdbc.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<% Connection con;
Statement sql;
ResultSet rs;
try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e)
{ out.print(e);
}
try { con=DriverManager.getConnection("jdbc:odbc:mymoon","sa","sa");
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM employee WHERE salary>3000");
out.print("
");
out.print("");
out.print(""+"雇员号");
out.print(" "+"姓名");
out.print(" "+"出生日期");
out.print(" "+"薪水");
out.print(" ");
while(rs.next())
{ out.print("");
out.print(""+rs.getString(1)+" ");
out.print(""+rs.getString(2)+" ");
out.print(""+rs.getDate("birthday")+" ");
out.print(""+rs.getFloat("salary")+" ");
out.print(" ") ;
}
out.print("
");
con.close();
}
catch(SQLException e)
{ out.print(e);
}
%>
例子2
showBySQLDriver.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<% Connection con;
Statement sql;
ResultSet rs;
try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e)
{ out.print(e);
}
try { String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
String user="sa";
String password="sa";
con=DriverManager.getConnection(uri,user,password);
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM employee WHERE salary>3000");
out.print("
");
out.print("");
out.print(""+"雇员号");
out.print(" "+"姓名");
out.print(" "+"出生日期");
out.print(" "+"薪水");
out.print(" ");
while(rs.next())
{ out.print("");
out.print(""+rs.getString(1)+" ");
out.print(""+rs.getString(2)+" ");
out.print(""+rs.getDate("birthday")+" ");
out.print(""+rs.getFloat("salary")+" ");
out.print(" ") ;
}
out.print("
");
con.close();
}
catch(SQLException e)
{ out.print(e);
}
%>
例子3
QueryBean.java
package database.operation;
import java.sql.*;
public class QueryBean
{ String databaseName=""; //数据库名
String tableName=""; //表名
String user="" ; //用户
String secret="" ; //密码
StringBuffer queryResult; //查询结果
public QueryBean()
{ queryResult=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e) {}
}
public void setDatabaseName(String s)
{ databaseName=s.trim();
queryResult=new StringBuffer();
}
public String getDatabaseName()
{ return databaseName;
}
public void setTableName(String s)
{ tableName=s.trim();
queryResult=new StringBuffer();
}
public String getTableName()
{ return tableName;
}
public void setSecret(String s)
{ secret=s.trim();
queryResult=new StringBuffer();
}
public String getSecret()
{ return secret;
}
public void setUser(String s)
{ user=s.trim();
queryResult=new StringBuffer();
}
public String getUser()
{ return user;
}
public StringBuffer getQueryResult()
{ Connection con;
Statement sql;
ResultSet rs;
try { queryResult.append("
");
String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;
String id=user;
String password=secret;
con=DriverManager.getConnection(uri,id,password);
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int 字段个数=0;
queryResult.append("");
while(rs1.next())
{ 字段个数++;
String clumnName=rs1.getString(4);
queryResult.append(""+clumnName+" ");
}
queryResult.append(" ");
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM "+tableName);
while(rs.next())
{ queryResult.append("");
for(int k=1;k<=字段个数;k++)
{ queryResult.append(""+rs.getString(k)+" ");
}
queryResult.append(" ");
}
queryResult.append("
");
con.close();
}
catch(SQLException e)
{ queryResult.append("请输入正确的用户名和密码");
}
return queryResult;
}
}
inquire.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.QueryBean" %>
在 表查询到记录:
例子4
RandomQueryBean.java
package database.operation;
import java.sql.*;
import java.util.*;
public class RandomQueryBean
{ String databaseName=""; //数据库名称
String tableName=""; //表的名字
int count; //记录总数
int randomNumber; //随机输出的记录数
StringBuffer randomQueryResult; //查询结果
Connection con;
Statement sql;
ResultSet rs;
public RandomQueryBean()
{ randomQueryResult=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e){ }
}
public void setDatabaseName(String s)
{ databaseName=s.trim();
randomQueryResult=new StringBuffer();
}
public String getDatabaseName()
{ return databaseName;
}
public void setTableName(String s)
{ tableName=s.trim();
randomQueryResult=new StringBuffer();
}
public String getTableName()
{ return tableName;
}
public void setRandomNumber(int n)
{ randomNumber=n;
randomQueryResult=new StringBuffer();
}
public int getRandomNumber()
{ return randomNumber;
}
public int getCount()
{ try{ String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;
con=DriverManager.getConnection(uri,"sa","sa");
sql= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs=sql.executeQuery("SELECT * FROM "+tableName);
rs.last();
count=rs.getRow();
con.close();
}
catch(SQLException exp)
{ count=-1;
}
return count;
}
public StringBuffer getRandomQueryResult()
{ randomQueryResult=new StringBuffer();
try { randomQueryResult.append("
");
String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;
con=DriverManager.getConnection(uri,"sa","sa");
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int 字段个数=0;
randomQueryResult.append("");
while(rs1.next())
{ 字段个数++;
String clumnName=rs1.getString(4);
randomQueryResult.append(""+clumnName+" ");
}
randomQueryResult.append(" ");
sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs=sql.executeQuery("SELECT * FROM "+tableName);
rs.last();
count=rs.getRow();
Vector vector=new Vector();
for(int i=1;i<=count;i++)
{ vector.add(new Integer(i));
}
int 抽取数目=Math.min(randomNumber,count);
while(抽取数目>0)
{ int i=(int)(Math.random()*vector.size());
int index=(vector.elementAt(i)).intValue();//vector中随机抽取一个元素
rs.absolute(index); //游标移到这一行
randomQueryResult.append("");
for(int k=1;k<=字段个数;k++)
{ randomQueryResult.append(""+rs.getString(k)+" ");
}
randomQueryResult.append(" ");
抽取数目--;
vector.removeElementAt(i); //将抽取过的元素从vector中删除
}
randomQueryResult.append("
");
con.close();
}
catch(SQLException e){ }
randomNumber=0;
return randomQueryResult;
}
}
random.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.*" %>
随机查询数据库表中的记录:
在 表中共有
条记录.
随机输出 条记录:
例子5
ConditionQuery.java
package database.operation;
import java.sql.*;
public class ConditionQuery
{ String number ; //雇员号
float salaryMax,salaryMin; //薪水范围
StringBuffer queryResultByNumber,
queryResultBySalary;
public ConditionQuery()
{ queryResultByNumber=new StringBuffer();
queryResultBySalary=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e){ }
}
public void setNumber(String s)
{ number=s.trim();
queryResultByNumber=new StringBuffer();
queryResultBySalary=new StringBuffer();
}
public String getNumber()
{ return number;
}
public void setSalaryMax(float n)
{ salaryMax=n;
queryResultByNumber=new StringBuffer();
queryResultBySalary=new StringBuffer();
}
public float getSalaryMax()
{ return salaryMax;
}
public void setSalaryMin(float n)
{ salaryMin=n;
queryResultByNumber=new StringBuffer();
queryResultBySalary=new StringBuffer();
}
public float getSalaryMin()
{ return salaryMin;
}
public StringBuffer getQueryResultByNumber()
{ String condition="SELECT * FROM employee Where number = '"+number+"'";
queryResultByNumber=f(condition);
return queryResultByNumber;
}
public StringBuffer getQueryResultBySalary()
{ String condition="SELECT * FROM employee Where salary <= "+salaryMax
+" AND "+"salary >= "+salaryMin;
queryResultBySalary=f(condition);
return queryResultBySalary;
}
private StringBuffer f(String condition)
{ StringBuffer str=new StringBuffer();
Connection con;
Statement sql;
ResultSet rs;
try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
con=DriverManager.getConnection(uri,"sa","sa");
sql=con.createStatement();
rs=sql.executeQuery(condition);
str.append("
");
str.append(""+"number");
str.append(" "+"name");
str.append(" "+"birthday");
str.append(" "+"salary");
while(rs.next())
{ str.append(" ");
str.append(""+rs.getString(1)+" ");
str.append(""+rs.getString(2)+" ");
str.append(""+rs.getDate(3)+" ");
str.append(""+rs.getFloat(4)+" ");
str.append(" ");
}
str.append("");
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
return str;
}
}
condition.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.*" %>
根据雇员号 查询到的记录:
薪水在 至
之间的记录:
例子6
OrderQuery.java
package database.operation;
import java.sql.*;
public class OrderQuery
{ String orderType; //排序方式
StringBuffer orderResult; //排序结果
public OrderQuery()
{ orderResult=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e){ }
}
public void setOrderType(String s)
{ orderType=s.trim();
try{ byte bb[]=orderType.getBytes("ISO-8859-1");
orderType=new String(bb,"gb2312");
}
catch(Exception e){}
}
public String getOrderType()
{ return orderType;
}
public StringBuffer getOrderResult()
{ String orderCondition="SELECT * FROM employee ORDER BY "+orderType;
Connection con;
Statement sql;
ResultSet rs;
try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
con=DriverManager.getConnection(uri,"sa","sa");
sql=con.createStatement();
rs=sql.executeQuery(orderCondition);
orderResult.append("");
orderResult.append(""+"number");
orderResult.append(" "+"name");
orderResult.append(" "+"birthday");
orderResult.append(" "+"salary");
while(rs.next())
{ orderResult.append(" ");
orderResult.append(""+rs.getString(1)+" ");
orderResult.append(""+rs.getString(2)+" ");
orderResult.append(""+rs.getDate(3)+" ");
orderResult.append(""+rs.getFloat(4)+" ");
orderResult.append(" ");
}
orderResult.append("");
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
return orderResult;
}
}
sort.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.*" %>
根据排序方式: ,排序的记录
例子7
KeyWordQuery.java
package database.operation;
import java.sql.*;
public class KeyWordQuery
{ String ziduan="", //字段
keyWord=""; //关键字
StringBuffer queryResult;
public KeyWordQuery()
{ queryResult=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e){ }
}
public void setKeyWord(String s)
{ keyWord=s.trim();
try{ byte bb[]=keyWord.getBytes("ISO-8859-1");
keyWord=new String(bb,"gb2312");
}
catch(Exception e){}
}
public String getKeyWord()
{ return keyWord;
}
public void setZiduan(String s)
{ ziduan=s.trim();
try{ byte bb[]=ziduan.getBytes("ISO-8859-1");
ziduan=new String(bb,"gb2312");
}
catch(Exception e){}
}
public String getZiduan()
{ return ziduan;
}
public StringBuffer getQueryResult()
{ String condition="SELECT * FROM employee Where "+ziduan+" Like '%"+keyWord+"%'";
StringBuffer str=f(condition);
return str;
}
public StringBuffer f(String condition)
{ StringBuffer str=new StringBuffer();
Connection con;
Statement sql;
ResultSet rs;
try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
con=DriverManager.getConnection(uri,"sa","sa");
sql=con.createStatement();
rs=sql.executeQuery(condition);
str.append("");
str.append(""+"雇员号");
str.append(" "+"姓名");
str.append(" "+"出生日期");
str.append(" "+"薪水");
while(rs.next())
{ str.append(" ");
str.append(""+rs.getString(1)+" ");
str.append(""+rs.getString(2)+" ");
str.append(""+rs.getDate(3)+" ");
str.append(""+rs.getString(4)+" ");
str.append(" ");
}
str.append("");
con.close();
}
catch(SQLException e)
{ System.out.println(e);
}
return str;
}
}
keyWord.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.*" %>
含有关键字
的记录:
例子8
AddBean.java
package database.operation;
import java.sql.*;
public class AddBean
{ String number="", //雇员号
name="", //姓名
birthday=""; //出生日期
float salary; //薪水
String addMessage="";
public AddBean()
{ try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e){ }
}
public void setNumber(String s)
{ number=s.trim();
}
public void setName(String s)
{ name=s.trim();
try{ byte bb[]=name.getBytes("ISO-8859-1");
name=new String(bb,"gb2312");
}
catch(Exception e){}
}
public void setBirthday(String s)
{ birthday=s.trim();
}
public void setSalary(float n)
{ salary=n;
}
public String getAddMessage()
{ String insertCondition="INSERT employee VALUES( '"+number+
"', '"+name+"','"+birthday+"',"+salary+")";
String str="";
Connection con;
Statement sql;
try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
con=DriverManager.getConnection(uri,"sa","sa");
sql=con.createStatement();
if(number.length()>0)
{ int m=sql.executeUpdate(insertCondition);
if(m!=0)
{ str="对表中添加"+m+"条记录成功";
}
else
{ str="添加记录失败";
}
}
else
{ str="必须要有雇员号";
}
con.close();
}
catch(SQLException e)
{ str="输入的雇员不允许重复"+e;
}
return str;
}
}
add.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<%@ page import="database.operation.*" %>
雇员号是主键,不可重复,请输入新记录的相应字段的值:
例子9
ShowRecordByPage.java
package database.operation;
import java.sql.*;
import com.sun.rowset.*;
public class ShowRecordByPage
{ int pageSize=10; //每页显示的记录数
int pageAllCount=0; //分页后的总页数
int showPage=1 ; //当前显示页
StringBuffer presentPageResult; //显示当前页内容
CachedRowSetImpl rowSet; //用于存储ResultSet对象
String databaseName=""; //数据库名称
String tableName=""; //表的名字
String user="" ; //用户
String password="" ; //密码
String 字段[]=new String[100] ;
int 字段个数=0;
public ShowRecordByPage()
{ presentPageResult=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
}
catch(Exception e){}
}
public void setPageSize(int size)
{ pageSize=size;
字段个数=0;
String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;
try{ Connection con=DriverManager.getConnection(uri,user,password);
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int k=0;
while(rs1.next())
{ 字段个数++;
字段[k]=rs1.getString(4); //获取字段的名字
k++;
}
Statement sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs=sql.executeQuery("SELECT * FROM "+tableName);
rowSet=new CachedRowSetImpl(); //创建行集对象
rowSet.populate(rs);
con.close(); //关闭连接
rowSet.last();
int m=rowSet.getRow(); //总行数
int n=pageSize;
pageAllCount=((m%n)==0)?(m/n):(m/n+1);
}
catch(Exception exp){}
}
public int getPageSize()
{ return pageSize;
}
public int getPageAllCount()
{ return pageAllCount;
}
public void setShowPage(int n)
{ showPage=n;
}
public int getShowPage()
{ return showPage;
}
public StringBuffer getPresentPageResult()
{ if(showPage>pageAllCount)
showPage=1;
if(showPage<=0)
showPage=pageAllCount;
presentPageResult=show(showPage);
return presentPageResult;
}
public StringBuffer show(int page)
{ StringBuffer str=new StringBuffer();
str.append("");
str.append("");
for(int i=0;i<字段个数;i++)
{ str.append(""+字段[i]+" ");
}
str.append(" ");
try{ rowSet.absolute((page-1)*pageSize+1);
for(int i=1;i<=pageSize;i++)
{ str.append("");
for(int k=1;k<=字段个数;k++)
{ str.append(""+rowSet.getString(k)+" ");
}
str.append(" ");
rowSet.next();
}
}
catch(SQLException exp){}
str.append("
");
return str;
}
public void setDatabaseName(String s)
{ databaseName=s.trim();
}
public String getDatabaseName()
{ return databaseName;
}
public void setTableName(String s)
{ tableName=s.trim();
}
public String getTableName()
{ return tableName;
}
public void setPassword(String s)
{ password=s.trim();;
}
public void setUser(String s)
{ user=s.trim();
}
public String getUser()
{ return user;
}
}
showByPage.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<%@ page import="database.operation.*" %>
数据库
中
表的记录将被分页显示。
共有 页.
每页最多显示 条记录。
当前显示第 页,
单击“前一页”或“下一页”按纽查看记录
例子10
linkOracle.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<% Connection con=null;
Statement sql=null;
ResultSet rs=null;
try{ Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e){}
try
{ con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.35:1521:Lea",
"scott","tiger");
sql=con.createStatement();
rs=sql.executeQuery("select * from emp");
out.print("");
out.print("");
out.print(""+"EMPNO");
out.print(" "+"Ename");
out.print(" ");
while(rs.next())
{ out.print("");
int n=rs.getInt(1);
out.print(""+n+" ");
String e=rs.getString(2);
out.print(""+e+" ");
out.print(" ") ;
}
out.print("
");
con.close();
}
catch(SQLException e1)
{out.print(""+e1);
}
%>
例子11
linkMySql.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<% Connection con;
Statement sql;
ResultSet rs;
try { Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e)
{ out.print(e);
}
try { String uri= "jdbc:mysql://localhost/factory";
con=DriverManager.getConnection(uri,"root","123");
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM employee");
out.print("");
while(rs.next())
{ out.print("");
out.print(""+rs.getString(1)+" ");
out.print(""+rs.getString(2)+" ");
out.print(""+rs.getDate(3)+" ");
out.print(""+rs.getFloat(4)+" ");
out.print(" ") ;
}
out.print("
");
con.close();
}
catch(SQLException e1)
{ out.print(e1);
}
%>
例子12
MySqlBean.java
package database.operation;
import java.sql.*;
public class MySqlBean
{ String databaseName=""; //数据库名
String tableName=""; //表名
String user="" ; //用户
String secret="" ; //密码
StringBuffer queryResult; //查询结果
public MySqlBean()
{ queryResult=new StringBuffer();
try{ Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){}
}
public void setDatabaseName(String s)
{ databaseName=s.trim();
queryResult=new StringBuffer();
}
public String getDatabaseName()
{ return databaseName;
}
public void setTableName(String s)
{ tableName=s.trim();
queryResult=new StringBuffer();
}
public String getTableName()
{ return tableName;
}
public void setSecret(String s)
{ secret=s.trim();
queryResult=new StringBuffer();
}
public String getSecret()
{ return secret;
}
public void setUser(String s)
{ user=s.trim();
queryResult=new StringBuffer();
}
public String getUser()
{ return user;
}
public StringBuffer getQueryResult()
{ Connection con;
Statement sql;
ResultSet rs;
try { queryResult.append("");
String uri= "jdbc:mysql://localhost/factory";
String user="root";
String password="123";
con=DriverManager.getConnection(uri,user,password);
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int 字段个数=0;
queryResult.append("");
while(rs1.next())
{ 字段个数++;
String clumnName=rs1.getString(4);
queryResult.append(""+clumnName+" ");
}
queryResult.append(" ");
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM "+tableName);
while(rs.next())
{ queryResult.append("");
for(int k=1;k<=字段个数;k++)
{ queryResult.append(""+rs.getString(k)+" ");
}
queryResult.append(" ");
}
queryResult.append("
");
con.close();
}
catch(SQLException e)
{ queryResult.append("请输入正确的用户名和密码");
}
return queryResult;
}
}
mysql.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.MySqlBean" %>
在 表查询到记录:
例子13
inquireExcel.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="java.sql.*" %>
<% Connection con;
Statement sql;
ResultSet rs;
try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e){}
try{ con=DriverManager.getConnection("jdbc:odbc:star","","");
sql=con.createStatement();
sql.executeUpdate("UPDATE message SET 品名='电缆线' WHERE 货号='ED56G'");
rs=sql.executeQuery("SELECT * FROM message");
out.print("");
out.print("");
out.print(""+"货号");
out.print(" "+"品名");
out.print(" "+"单位");
out.print(" "+"单价");
out.print(" "+"库存");
out.print(" ");
while(rs.next())
{ out.print("");
out.print(""+rs.getString(1)+" ");
out.print(""+rs.getString(2)+" ");
out.print(""+rs.getString(3)+" ");
out.print(""+rs.getString(4)+" ");
out.print(""+rs.getString(5)+" ");
out.print(" ") ;
}
out.print("
");
con.close();
}
catch(SQLException e1) {}
%>
例子14
ApplicationCon.java
package database.operation;
import java.sql.*;
import java.util.LinkedList;
public class ApplcationCon
{ LinkedList list; //存放Connection对象的链表
public ApplcationCon()
{ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e) {}
list=new LinkedList();
for(int k=0;k<=10;k++) 创建10个连接
{ try{
String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
String id="sa";
String password="sa";
Connection con=DriverManager.getConnection(uri,id,password);
list.add(con);
}
catch(SQLException e){}
}
}
public synchronized Connection getOneConnetion()
{ if(list.size()>0)
return list.removeFirst();//链表删除第一个节点,并返回该节点中的连接对象
else
return null;
}
public synchronized void putBackOneConnetion(Connection con)
{ list.addFirst(con);
}
}
UseConBean.java
package database.operation;
import java.sql.*;
public class UseConBean
{ String tableName=""; //表名
StringBuffer queryResult; //查询结果
Connection con;
public UseConBean()
{ queryResult=new StringBuffer();
}
public void setTableName(String s)
{ tableName=s.trim();
queryResult=new StringBuffer();
}
public String getTableName()
{ return tableName;
}
public void setConnection(Connection con)
{ this.con=con;
}
public StringBuffer getQueryResult()
{ Statement sql;
ResultSet rs;
try{ queryResult.append("");
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int 字段个数=0;
queryResult.append("");
while(rs1.next())
{ 字段个数++;
String clumnName=rs1.getString(4);
queryResult.append(""+clumnName+" ");
}
queryResult.append(" ");
sql=con.createStatement();
rs=sql.executeQuery("SELECT * FROM "+tableName);
while(rs.next())
{ queryResult.append("");
for(int k=1;k<=字段个数;k++)
{ queryResult.append(""+rs.getString(k)+" ");
}
queryResult.append(" ");
}
queryResult.append("
");
}
catch(SQLException e)
{ queryResult.append("请输入正确的表名"+e);
}
return queryResult;
}
}
chaxun.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import="database.operation.*" %>
<%@ page import="java.sql.*" %>
<% Connection connection=conSet.getOneConnetion();
inquire.setConnection(connection);
%>
你连接的数据库是factory
在 表查询到记录:
<% conSet.putBackOneConnetion(connection);
%>
例子15
PreparedQueryBean.java
package database.operation;
import java.sql.*;
public class PreparedQueryBean
{ String databaseName=""; //数据库名称
String tableName=""; //表的名字
String user="" ; //用户
String password="" ; //密码
StringBuffer queryResult; //查询结果
public PreparedQueryBean()
{ queryResult=new StringBuffer();
try{ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(Exception e)
{ queryResult=new StringBuffer();
queryResult.append(""+e);
}
}
public void setDatabaseName(String s)
{ queryResult=new StringBuffer();
databaseName=s.trim();
}
public String getDatabaseName()
{ return databaseName;
}
public void setTableName(String s)
{ queryResult=new StringBuffer();
tableName=s.trim();
}
public String getTableName()
{ return tableName;
}
public void setPassword(String s)
{ password=s.trim();;
}
public String getPassword()
{ return password;
}
public void setUser(String s)
{ user=s.trim();;
}
public String getUser()
{ return user;
}
public StringBuffer getQueryResult()
{ Connection con;
PreparedStatement sql;
ResultSet rs;
try { queryResult.append("");
String uri= "jdbc:sqlserver://127.0.0.1:1433;DatabaseName="+databaseName;
con=DriverManager.getConnection(uri,user,password);
DatabaseMetaData metadata=con.getMetaData();
ResultSet rs1=metadata.getColumns(null,null,tableName,null);
int 字段个数=0;
queryResult.append("");
while(rs1.next())
{ 字段个数++;
String clumnName=rs1.getString(4);
queryResult.append(""+clumnName+" ");
}
queryResult.append(" ");
sql=con.prepareStatement("SELECT * FROM "+tableName); //预处理语句
rs=sql.executeQuery();
while(rs.next())
{ queryResult.append("");
for(int k=1;k<=字段个数;k++)
{ queryResult.append(""+rs.getString(k)+" ");
}
queryResult.append(" ");
}
queryResult.append("
");
con.close();
}
catch(SQLException e)
{ queryResult.append(e);
}
return queryResult;
}
}
pre.jsp
<%@ page contentType="text/html;charset=GB2312" %>
<%@ page import=" database.operation.PreparedQueryBean" %>
使用预处理语句查询数据库:
例子16
AddRecordBean.java
package database.operation;
import java.sql.*;
public class AddRecordBean
{ String number="", //雇员号
name="", //姓名
birthday; //出生日期
float salary; //薪水
boolean ok=false;
public AddRecordBean()
{ try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(ClassNotFoundException e){}
}
public void setNumber(String s)
{ number=s.trim();
try{ byte bb[]=number.getBytes("ISO-8859-1");
number=new String(bb,"gb2312");
}
catch(Exception e){}
}
public void setName(String s)
{ name=s.trim();
try{ byte bb[]=name.getBytes("ISO-8859-1");
name=new String(bb,"gb2312");
}
catch(Exception e){}
}
public void setSalary(float n)
{ salary=n;
}
public void setBirthday(String b)
{ birthday=b;
}
public boolean getOk()
{ return ok;
}
public String getAddMessage()
{ String str="";
Connection con;
PreparedStatement sql;
try { String uri="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=factory";
con=DriverManager.getConnection(uri,"sa","sa");
String insertCondition="INSERT INTO employee VALUES (?,?,?,?)";
sql=con.prepareStatement(insertCondition);
if(number.length()>0)
{ sql.setString(1,number);
sql.setString(2,name);
sql.setString(3,birthday);
sql.setFloat(4,salary);
int m=sql.executeUpdate();
if(m!=0)
{ str="对表中添加"+m+"条记录成功";
ok=true;
}
else
{ str="添加记录失败";
}
}
else
{ str="必须要有雇员号";
}
con.close();
}
catch(SQLException e)
{ str="你还没有提供添加的数据或"+e;
}
return str;
}
}
addRecord.jsp
<%@ page contentType="text/html;charset=GB2312"%>
<%@ page import="java.sql.*" %>
<%@ page import="database.operation.ConditionQuery"%>
<%@ page import="database.operation.AddRecordBean"%>
雇员号是主键,不可重复,请输入新记录的相应字段的值:
你添加记录操作的结果:
添加的记录是:
<% if(add.getOk()==true)
{
%>
<% }
%>
你可能感兴趣的:(jsp教学,jsp,string,sqlserver,exception,数据库,input)