Java程序向数据库中插入数据,代码如下:
//首先创建数据库,(access,oracle,mysql,sqlsever)其中之一,其中access,sqlsever需要配置数据源(odbc);//然后再eclipse中创建类(ConnDb,Test,TestBean)ConnDb功能为连接数据库,查询,插入,删除,修改数据的类,Test为含有main方法的测试类,TestBean为数据表中的字段属性及set,get方法//以下是ConnDb代码:package db;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;public class ConnDb {public Connection startConn(Connection conn){ try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cOnn= DriverManager.getConnection("jdbc:odbc:数据库","用户名", "密码"); } catch (Exception e) { System.out.println("连接数据库时出现错误"); } return conn; } public ArrayList executeQuery(String sql){ Connection cOnn= null; Statement stmt = null; ResultSet rs = null; ArrayList list = new ArrayList(); try { cOnn= startConn(conn); stmt = conn.createStatement(); rs = stmt.executeQuery(sql);//sql为sql语句例如"select * from 表名",从main方法中传进来,这里用的是ArrayList 类将查询结果存储起来 while(rs.next()){ TestBean tb = new TestBean(); tb.setTid(rs.getString("tid")); tb.setTname(rs.getString("tname")); tb.setTinfo(rs.getString("tinfo")); list.add(tb); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ closeConn(rs,stmt,conn); } return list; } public void executeUpdate(String sql){ Connection cOnn= null; Statement stmt = null; try { cOnn= startConn(conn); stmt = conn.createStatement(); stmt.executeUpdate(sql); } catch (SQLException e) { System.out.println("修改,插入或者删除数据库数据时发生错误!"); }finally{ closeConn(stmt,conn); } } public void closeConn(ResultSet rs,Statement stmt,Connection conn){ try { if(rs != null){ rs.close(); } if(stmt != null){ stmt.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("关闭数据库的时候发生错误!"); } } public void closeConn(Statement stmt,Connection conn){ try { if(stmt != null){ stmt.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("关闭数据库的时候发生错误!"); } }}
按照你的要求编写的Java程序如下
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableRowSorter;
public class E extends JFrame implements KeyListener{
String[] columnTitle={"书名","图书作者","发行时间","价格"};
Object[][]data={{new String(),new String(),new Date(),0.0}};
DefaultTableModel model = new DefaultTableModel(data,columnTitle){
public Class getColumnClass(int column) {
Class returnValue;
if (column == 2 || column==3){
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
};
JTable jt=new JTable(model);
JScrollPane jsp=new JScrollPane(jt);
E(){
setTitle("表格测试");
jt.addKeyListener(this);
TableColumnModel tcm=jt.getColumnModel();
TableColumn tc=tcm.getColumn(0);
tc.setPreferredWidth(250);
TableColumn tc1=tcm.getColumn(1);
tc1.setPreferredWidth(75);
TableColumn tc2=tcm.getColumn(2);
tc2.setPreferredWidth(75);
TableColumn tc3=tcm.getColumn(3);
tc3.setPreferredWidth(200);
RowSorter sorter = new TableRowSorter(model);
jt.setRowSorter(sorter);
add(jsp);
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER){//在最后一行最后一列单元格处,按回车键表格增加一个空行
int column=jt.getColumnCount()-1;
int row=jt.getRowCount()-1;
if(column==jt.getSelectedColumn() row==jt.getSelectedRow()){
Object[] empty={new String(),new String(),new Date(),0.0};
model.addRow(empty);
}
}
if(e.getKeyCode()==KeyEvent.VK_INSERT){//按Insert键插入一个空行
Object[] empty={new String(),new String(),new Date(),0.0};
model.insertRow(jt.getSelectedRow(),empty);
}
if(e.getKeyCode()==KeyEvent.VK_DELETE){//按Delete键删除当前行
model.removeRow(jt.getSelectedRow());
}
}
@Override
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
new E();
}
}
运行结果(按价格升序排列,点表头可实现相应列升降序排序)
package ch02;
public class TEST{
public static void main(String[] args) {
for (int i = 1; i =9; i++) {
for (int j = 1; j = i; j++) {
System.out.print(j+"*"+i+"="+(i*j)+" ");
}System.out.println();
}
}
}
测试结果 :
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
实现思路:如果我们把九九乘法表中如“1*1=1”等式全部看作一个个整体的话,九九乘法表可看作一个直角三角形,实现直角三角形可用两个for循环嵌套来实现,那么我们最后输出应为System.out.print(变量1+"*"+变量2+"="+(变量1*变量2)+" ");
代码如下:
public class ChengDemo {
public static void main(String args[]){
for(int k = 1;k=9;k++){ //外循环用于控制行数
for(int j = 1;j=k;j++){
System.out.print(j+"*"+k+"="+(j*k)+"\t"); //"\t"为制表符
}
System.out.println(); //换行
}
}
}
一:页面图片显示预览:
1)如下图:
2)点击导出按钮后预览:
3)最终生成的excel表格图片预览:
二:代码演示:
说明:执行操作时,请先引进导出excel表格的jar文件包。
找到导出按钮所执行的js方法,在java后天查看该方法的实现即可。
1)jsp代码:
[html] view plaincopyprint?
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%
%@taglib prefix="s" uri="/struts-tags" %
%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%
html
head
base href="%=basePath%"
title驾校合格率排名/title
link href="jsp/commonstyle/css/tabStyle.css" rel="stylesheet" type="text/css"
link rel="STYLESHEET" type="text/css" href="%=basePath%jsp/hgltj/js/tablesort.css"
script type="text/Javascript" src="%=basePath%jsp/system/common/js/publicColor.js"/script
script type="text/Javascript" src="jsp/commonstyle/js/js/My97DatePicker/WdatePicker.js" defer="defer"/script
script type="text/Javascript" src="%=basePath%jsp/hgltj/js/tablesort.js"/script
script language="Javascript"
function load()
{
//根据分辨率设置表格大小
maxw=document.getElementById("maintb").offsetWidth;
if(maxw824){//1024分辨率未展开
mainbox.;
} else if(maxw1013){//1024分辨率展开
mainbox.;
} else if(maxw1081){//1280分辨率未展开
mainbox.;
} else if(maxw1270){//1280分辨未展开
mainbox.;
}else{//1280以上分辨展开
mainbox.;
}
}
/script
script
function overIt(){
var the_obj = event.srcElement;
if(the_obj.tagName.toLowerCase() == "td"){
the_obj=the_obj.parentElement;
the_obj.oBgc=the_obj.currentStyle.backgroundColor;
the_obj.oFc=the_obj.currentStyle.color;
the_obj.style.backgroundColor='#4073C4';
the_obj.style.color='#ffffff';
the_obj.style.textDecoration='underline';
}
}
function outIt(){
var the_obj = event.srcElement;
if(the_obj.tagName.toLowerCase() == "td"){
the_obj=the_obj.parentElement;
the_obj.style.backgroundColor=the_obj.oBgc;
the_obj.style.color=the_obj.oFc;
the_obj.style.textDecoration='';
}
}
function serch(){
document.getElementById("formName").action="%=basePath %hgltj.action?method=getHglpm";
document.getElementById("formName").submit();
}
function tbbt(){
var jzrq=document.getElementById("jzrqId").value;
//var jxmc=document.getElementById("jxmcId").value;
window.open('%=basePath %hgltj.action?method=getHglpmTbtjjxkshgl.jzrq='+jzrq+'tjjxkshgl.zt='+1,'','formName").action="%=basePath %hgltj.action?method=downJxhglPm";
document.getElementById("formName").submit();
}
/script
/head
BODY OnLoad="load()"
input type="hidden" name="method" value="getDriverInfoList"/
table border="0" cellspacing="0" cellpadding="0" id="maintb"
tr
td align="center"
table border="0" cellspacing="0" cellpadding="0" id="mainbox"
!--宽度可变内容框--
tr
td /td
td class="style1"font color="black"驾校合格率排名/font/td
td /td
/tr
tr
td colspan="3"
!--页面主体内容开始--
!--查询条件--
form action="" name="formName" method="post" id="formName" theme="simple"
table border="0" cellpadding="0" cellspacing="0" id="tj" align="center"
tr align="left"
td class="tjbg1"
!-- input type="hidden" id="method" name="method" value="getHglpm"/ --
统计日期:
input type="text" name="tjjxkshgl.jzrq" id="jzrqId" value="s:property value="tjjxkshgl.jzrq"/" Onclick="WdatePicker({skin:'whyGreen',dateFmt:'yyyy-MM'})"/
!-- 驾校名称:
s:select id="jxmcId" name="tjjxkshgl.jxxh" value="tjjxkshgl.jxxh" list="schoolList" listKey="jxxh" listValue="jxmc" headerKey="" headerValue="--请选择--" theme="simple"/s:select --
input name="input" value=" 统 计 " type="button" class="normalbtn" OnClick="serch()" /
input name="input" type="button" value=" 合格率图表 " Onclick="tbbt()" class="normalbtn" /
input id="Button1" type="button" value=" 导 出 " Onclick="openwd();" class="normalbtn" /
/td
/tr
/table!--查询结果--
/form
!--查询结果--
table border="0" cellpadding="4" cellspacing="1" bgcolor="#abcfff" id="cxjg" align="center"
thead
tr class="tbtitle"
td align="center" class="t1"名次/td
td align="center" class="t1"名称/td
td class="t1" align="center"科目一/td
td class="t1" align="center"科目二/td
td class="t1" align="center"科目三/td
td class="t1" align="center"平均合格率/td
td class="t1" align="center"操作/td
/tr
/thead
s:iterator id="jxhgl" value="jxhelpmList" status="st"
tr class="changeColor" OnMouseOver="overIt()" OnMouseOut="outIt()" align="center"
tds:property value="#st.index+1"//td
tds:property value="#jxhgl.jxmc"//td
tds:property value="#jxhgl.km1hgl"//td
tds:property value="#jxhgl.km2hgl"//td
tds:property value="#jxhgl.km3hgl"//td
tds:property value="#jxhgl.avghgl"/%/td
td
a href="Javascript:" Onclick="openWin('%=basePath %hgltj.action?method=getTbForJxxhtjjxkshgl.jxxh=s:property value="#jxhgl.jxxh"/tjjxkshgl.zt=1','',1250,750);"图表/a
/td
/tr
/s:iterator
/table
/table
/td
/tr
/table
/body
/html
2)java代码演示:
[java] view plaincopyprint?
/**
* 驾校合格率导出excel图表
*/
//response.getOutputStream();// 取得输出流
response.reset();// 清空输出流
String tmptitle = "驾校合格率排名"; // 标题
response.setHeader("Content-disposition", "attachment; filename="+new String(tmptitle.getBytes(),"iso8859-1")+".xls");// 设定输出文件头
response.setContentType("application/vnd.ms-excel");// 定义输出类型
wbook = Workbook.createWorkbook(os); // 建立excel文件
WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
// 设置excel标题
//cellFormat.setBackground(Colour.AQUA);
cellFormat.setFont(wfont);
label.setCellFormat(cellFormat);
wsheet.addCell(label);
//wsheet.addCell(new Label(0, 0, tmptitle, wcfFC));
wsheet.setRowView(0,500); //第一行高度
wsheet.mergeCells(0, 0, 6, 1); //合并单元格(第一列的第一行和第七列的第二行合并)
//wsheet.mergeCells(0, 1, 9, 1);
// wsheet.mergeCells(0, 2, 0, 4);
// wsheet.mergeCells(1, 2, 3, 2);
// wsheet.mergeCells(4, 2, 6, 2);
// wsheet.mergeCells(7, 2, 9, 2);
wsheet.setColumnView(0,10); //宽度
wsheet.setColumnView(1,25); //宽度
wsheet.setColumnView(2,10); //宽度
wsheet.setColumnView(3,10); //宽度
wsheet.setColumnView(4,10); //宽度
wsheet.setColumnView(5,10); //宽度
// 开始生成主体内容
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,WritableFont.BOLD,false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK);
wcfFC = new WritableCellFormat(wfont);
wsheet.addCell(new Label(0, 2, "名次",wcfFC));
wsheet.addCell(new Label(1, 2, "驾校名称",wcfFC));
wsheet.addCell(new Label(2, 2, "科目一",wcfFC));
wsheet.addCell(new Label(3, 2, "科目二",wcfFC));
wsheet.addCell(new Label(4, 2, "科目三",wcfFC));
wsheet.addCell(new Label(5, 2, "合格率",wcfFC));
int count=jxhelpmList.size();
if(count0){ ////判断集合是否不为0
TjJxkshgl tjhgl=null;
for(int i=0;ijxhelpmList.size();i++){
tjhgl=(TjJxkshgl)jxhelpmList.get(i);
wsheet.addCell(new Label(0, i+3, (i+1)+""));
wsheet.addCell(new Label(1, i+3, tjhgl.getJxmc()));
wsheet.addCell(new Label(2, i+3, tjhgl.getKm1hgl()));
wsheet.addCell(new Label(3, i+3, tjhgl.getKm2hgl()));
wsheet.addCell(new Label(4, i+3, tjhgl.getKm3hgl()));
wsheet.addCell(new Label(5, i+3, tjhgl.getAvghgl()));
}
Swing是MVC架构,所以你修改模型层,显示层就随之而变。也就是说你先对数据进行排序,然后再放到表格组件中。