java,
java,
.Java数据库连接
import java.sql.*;
public class ConDB {
public static Connection getCon() {
Connection con = null;
// try {
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// } catch (ClassNotFoundException ex) {
// System.out.println(ex);
// }
//
// try {
// String url = "jdbc:odbc:xcc";
// con = DriverManager.getConnection(url);
// } catch (SQLException ex1) {
// System.out.println(ex1);
// }
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
} catch (ClassNotFoundException ex) {
System.out.println(ex);
}
try {
con = DriverManager.getConnection(
"jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=exam","sa","");
} catch (SQLException ex1) {
System.out.println(ex1);
}
return con;
}
}
2.Java调用储存过程
java.sql.CallableStatement cs = null;
String strcall = "{ call xcc(?,?)}";
try {
cs = con.prepareCall(strcall);
cs.setString(1, "aa");
cs.registerOutParameter(2, java.sql.Types.INTEGER);
cs.execute();
int count = cs.getInt(2);
JOptionPane.showMessageDialog(null, "bb" + count + " 位",
"bb",
1);
} catch (SQLException ex) {
System.out.println("儲存過程出錯");
}
3.JSP显示参数乱码处理
String s =new String(request.getParameter("name").getBytes("ISO-8859-1"),"GBK");
4.Java文件操作
输入输出流
在Java中,我们把能够读取一个字节序列的对象称作一个输入流;而我们把够写一个字节序列称作一个输出流。它们分别由抽象类
InputStream和OutputStream类表示。因为面向字节的流不方便用来处理存储为Unicode(每个字符使用两个字节)的信息。所以Java
引入了用来处理Unicode字符的类层次,这些类派生自抽象类Reader和Writer,它们用于读写双字节的Unicode字符,而不是单字节字符。
Java.io包简介
JDK标准帮助文档是这样解释Java.io包的,通过数据流、序列和文件系统为系统提供输入输出。
InputStream类和OutputStream类
InputStream类是所有输入数据流的父类,它是一个抽象类,定义了所有输入数据流都具有的共通特性。
java.io.InputStream的方法如下:
public abstract read()throws IOException
读取一个字节并返回该字节,如果到输入源的末则返回-1。一个具体的输入流类需要重载此方法,以提供 有用的功能。例如:在FileInputStream类中,该方法从一个文件读取一个字节。
public int read(byte[] b)throws IOException
把数据读入到一个字节数据中,并返回实际读取的字节数目。如果遇到流末 则返回-1,该方法最多读取b.length个字节。
public abstract int read(byte[] b,int off,int len)throws IOException
把数据读入到一个字节数组中并返回实际读取的字节数目。如果遇到流的末尾则的返回-1。 其中参数off表示第一个字节在b中的位置,len表示读取的最大字节数。
public long skip(long n)throws IOException
略过N个字节不读取,会返回实际略过的字节数目。因为数据流中剩下的数据可能不到N 个字节那么多,所以此时返回值会小于N。
public int available()throws IOException
read方法(包括后面要讲的OutputStream类的Write方法)都能够阴塞一个线程,直到字节被 实际读取或写入。这意味着如果一个流不能立即被读或被写
/*
* Created on 2005-3-10
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package mytestfiles;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author zhangqinglin
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class Files
{
public static void main(String[] args) throws IOException
{
Files f = new Files();
// System.out.println(f.readFile("f:/LinkFile.java"));
// f.readAllFile("f:/","LinkFile.java");
// f.readLineFile("f:/","LinkFile.java");
// System.out.println(f.fileIsNull("f:/","122.txt"));
// f.readFolderByFile("F:/PDF");
// System.out.println(f.createAndDeleteFolder("ss","f:/"));
// System.out.println(f.createAndDeleteFile("f:/ss/","TestFile.dat"));
String[] ss = new String[50];
for(int i=0;i<ss.length;i++)
{
ss[i] = "信息技术和互联网(计算机软硬件,通讯) "+i;
}
f.writeFile("f:/ss/","TestFile.txt",ss);
}
/**
* 文件的写入
* @param filePath(文件路径)
* @param fileName(文件名)
* @param args[]
* @throws IOException
*/
public void writeFile(String filePath,String fileName,String[] args) throws IOException
{
FileWriter fw = new FileWriter(filePath+fileName);
PrintWriter out=new PrintWriter(fw);
for(int i=0;i<args.length;i++)
{
out.write(args[i]);
out.println();
out.flush();
}
fw.close();
out.close();
}
/**
* 文件的写入
* @param filePath(文件路径)
* @param fileName(文件名)
* @param args
* @throws IOException
*/
public void writeFile(String filePath,String fileName,String args) throws IOException
{
FileWriter fw = new FileWriter(filePath+fileName);
fw.write(args);
fw.close();
}
/**
* 创建与删除文件
* @param filePath
* @param fileName
* @return 创建成功返回true
* @throws IOException
*/
public boolean createAndDeleteFile(String filePath,String fileName) throws IOException
{
boolean result = false;
File file = new File(filePath,fileName);
if(file.exists())
{
file.delete();
result = true;
System.out.println("文件已经删除!");
}
else
{
file.createNewFile();
result = true;
System.out.println("文件已经创建!");
}
return result;
}
/**
* 创建和删除目录
* @param folderName
* @param filePath
* @return 删除成功返回true
*/
public boolean createAndDeleteFolder(String folderName,String filePath)
{
boolean result = false;
try
{
File file = new File(filePath+folderName);
if(file.exists())
{
file.delete();
System.out.println("目录已经存在,已删除!");
result = true;
}
else
{
file.mkdir();
System.out.println("目录不存在,已经建立!");
result = true;
}
}
catch(Exception ex)
{
result = false;
System.out.println("CreateAndDeleteFolder is error:"+ex);
}
return result;
}
/**
* 输出目录中的所有文件及目录名字
* @param filePath
*/
public void readFolderByFile(String filePath)
{
File file = new File(filePath);
File[] tempFile = file.listFiles();
for(int i = 0;i<tempFile.length;i++)
{
if(tempFile[i].isFile())
{
System.out.println("File : "+tempFile[i].getName());
}
if(tempFile[i].isDirectory())
{
System.out.println("Directory : "+tempFile[i].getName());
}
}
}
/**
* 检查文件中是否为一个空
* @param filePath
* @param fileName
* @return 为空返回true
* @throws IOException
*/
public boolean fileIsNull(String filePath,String fileName) throws IOException
{
boolean result = false;
FileReader fr = new FileReader(filePath+fileName);
if(fr.read() == -1)
{
result = true;
System.out.println(fileName+" 文件中没有数据!");
}
else
{
System.out.println(fileName+" 文件中有数据!");
}
fr.close();
return result;
}
/**
* 读取文件中的所有内容
* @param filePath
* @param fileName
* @throws IOException
*/
public void readAllFile(String filePath,String fileName) throws IOException
{
FileReader fr = new FileReader(filePath+fileName);
int count = fr.read();
while(count != -1)
{
System.out.print((char)count);
count = fr.read();
if(count == 13)
{
fr.skip(1);
}
}
fr.close();
}
/**
* 一行一行的读取文件中的数据
* @param filePath
* @param fileName
* @throws IOException
*/
public void readLineFile(String filePath,String fileName) throws IOException
{
FileReader fr = new FileReader(filePath+fileName);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null)
{
System.out.println(line);
line = br.readLine();
}
br.close();
fr.close();
}
}
获取某一目录下的文件列表
File MyDir = new File("C:/Windows/.");
String[] FileNames = MyDir.list();
5.Java数据库文件生成XML文档
public static void main(String[] args) {
Connection con = ConDB.Con();
PreparedStatement pst = null;
ResultSet rs = null;
String colName;
try {
pst = con.prepareStatement("SELECT * FROM master");
rs = pst.executeQuery();
Document document = new Document(new Element("根元素")); //创建文档,并设根无素
ResultSetMetaData rsmd = rs.getMetaData(); //获取字段名,返回ResultSetMetaData对像
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
Element element0 = new Element("users"); //创建元素 生成JDOM树
document.getRootElement().addContent(element0);
// Element element2 = new Element("userphone");
// element0.addContent(element2);
for (int i = 1; i <= numberOfColumns; i++) {
try {
// colName = new String(rs.getString(i).getBytes(
// "ISO-8859-1"),
// "gbk"); //代码转换,好像用不着
colName = new String(rs.getString(i));
//构造元素节点和文本节点
Element element = new Element(rsmd.getColumnName(i)).setText(colName);
element0.addContent(element);
} catch (SQLException ex1) {
}
}
}
//org.jdom.output.XMLOutputter
XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
try {
//生成XML文件路径
outp.output(document,new FileOutputStream("userinfo.xml"));
} catch (IOException ex2) {
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
6.Java读取XML数据插入数据库.
import java.sql.*;
import java.util.*;
import c.ConDB;
import org.xml.sax.*;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import java.io.*;
import org.apache.xerces.parsers.*;
public class XMLInsetDB {
public static void main(String[] args) {
Connection con = ConDB.Con();
PreparedStatement pst = null;
try {
//读入XML文件
BufferedReader br = new BufferedReader(new FileReader("a.xml"));
DOMParser parser = new DOMParser();
parser.parse(new InputSource(br));
//获取Document对像
org.w3c.dom.Document doc = parser.getDocument();
//获取所有节点,返回 Nodelist组
org.w3c.dom.NodeList nl = doc.getElementsByTagName("*");
String s = "";//构建SQL语句的值连接字符串
int b = 0;//控制次数
for (int i = 0; i < nl.getLength(); i++) {
//获取元素节点
Node n = nl.item(i);
//取值判断,连接成SQL语句
if (n.getParentNode().getNodeName().equals("users")) {
if (b <= 3) {
s = s +"'"+ n.getFirstChild().getNodeValue() + "',";
b++;
if (b > 3) {
String str = s.substring(0, s.length() - 1);
System.out.println(str);
pst = con.prepareStatement("INSERT INTO master (主人编号, 主人姓名, 电话, 地址) VALUES ("+str+")");
pst.executeUpdate();
s = "";
b = 0;
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
7.JSP分页.
public ArrayList fenPage(int intPage){
int pageRow = intPage * 3;
ArrayList list = new ArrayList();
PreparedStatement pst = null;
ResultSet rs = null;
Connection con = ConDB.Con();
try {
pst = con.prepareStatement(
"select top 3 * from pet where not 宠物编号<="+pageRow+"");
rs = pst.executeQuery();
while(rs.next()){
Pet p = new Pet();
p.setPetId(rs.getInt(1));
p.setPetName(rs.getString(2));
p.setMasterId(rs.getInt(3));
list.add(p);
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
<%@page contentType="text/html; charset=GBK"%>
<html>
<head>
<title>JSP分页</title>
</head>
<body bgcolor="#ffffff">
<h1>JSP分页</h1>
<table border="1">
<thead>
<tr>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<%
c.ToPet tp = new c.ToPet();
String str = request.getParameter("pageCount");
int intPageCount = 0;
if (str != null) {
intPageCount = Integer.parseInt(str);
}
java.util.ArrayList list = tp.fenPage(intPageCount);
for (int i = 0; i < list.size(); i++) {
v.Pet p = (v.Pet) list.get(i);
%>
<tr>
<td><%=p.getPetId() %> </td>
<td><%=p.getPetName() %> </td>
</tr>
<%}%>
<tr>
<td align="center">
<a href="jsp1.jsp?pageCount=<%=intPageCount+1%>">下一页</a>
</td>
<td align="center">
<%if (intPageCount > 0) { %>
<a href="jsp1.jsp?pageCount=<%=intPageCount-1%>">上一页</a>
<%} %>
</td>
</tr>
</table>
</body>
</html>
.JSP生成签证码.
<%@page contentType="image/jpeg" import="java.awt.*, java.awt.image.*,java.util.*,javax.imageio.*"%>
<%
// 在内存中创建图象
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
// 设定背景色
g.setColor(new Color(0xDCDCDC));
g.fillRect(0, 0, width, height);
//画边框
g.setColor(Color.black);
g.drawRect(0, 0, width - 1, height - 1);
// 取随机产生的认证码(4位数字)
// String rand = request.getParameter("rand");
// rand = rand.substring(0, rand.indexOf("."));
// switch (rand.length()) {
// case 1:
// rand = "000" + rand;
// break;
// case 2:
// rand = "00" + rand;
// break;
// case 3:
// rand = "0" + rand;
// break;
// default:
// rand = rand.substring(0, 4);
// break;
// }
Random r = new Random();
int a = r.nextInt(9);
int b = r.nextInt(9);
int c = r.nextInt(9);
int d = r.nextInt(9);
String rand = a+""+b+""+c+""+d+"";
// 将认证码存入SESSION
session.setAttribute("rand", rand);
// 将认证码显示到图象中
g.setColor(Color.black);
Integer tempNumber = new Integer(rand);
String numberStr = tempNumber.toString();
g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));
String Str = numberStr.substring(0, 1);
g.drawString(Str, 8, 17);
Str = numberStr.substring(1, 2);
g.drawString(Str, 20, 15);
Str = numberStr.substring(2, 3);
g.drawString(Str, 35, 18);
Str = numberStr.substring(3, 4);
g.drawString(Str, 45, 15);
// 随机产生88个干扰点,使图象中的认证码不易被其它程序探测到
Random random = new Random();
for (int i = 0; i < 88; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawOval(x, y, 0, 0);
}
// 图象生效
g.dispose();
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
相关文章
- 暂无相关文章
用户点评