package shujvdaochu;
public interface Export {
public boolean export(String data);
}
package gongchang;
import java.sql.*;
public class ExportDb implements Export {
public boolean export(String data) throws ClassNotFoundException, SQLException {
System.out.println("导出数据"+data+"到数据库");
String driveName="com.mysql.jdbc.Driver";
String userName="root";
String userPwd="031116";
String dbName="sheji";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user="+userName+"&password="+userPwd;
String url3="&useUnicode=true&characterEncoding=UTF-8";
String url=url1+url2+url3;
Class.forName(driveName);
Connection conn=DriverManager.getConnection(url);
String sql="insert into shujv values(?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1,data);
int n=pstmt.executeUpdate();
if(n>=1)
System.out.println("数据库操作成功");
else
System.out.println("数据库操作失败");
if(pstmt!=null)
{pstmt.close();}
if(conn!=null)
{conn.close();
}
return true;
}
}
package gongchang;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ExportTxt implements Export {
public boolean export(String data) throws IOException {
System.out.println("导出数据"+data+"到文件");
File f1=new File("d:\\gwh.txt");
FileWriter fw=new FileWriter(f1);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(data);
bw.close();
return true;
}
}
package shujvdaochu;
public abstract class ExportFactory {
public boolean export(String data)
{
Export api=factoryMethod();
return api.export(data);
}
protected abstract Export factoryMethod();
}
package shujvdaochu;
public class DbFactory extends ExportFactory {
@Override
protected Export factoryMethod() {
return new ExportDb();
}
}
package shujvdaochu;
public class Txtfactory extends ExportFactory {
@Override
protected Export factoryMethod() {
return new ExportTxt();
}
}
package shujvdaochu;
public class Test {
public static void main(String args[])
{ExportFactory ef=new DbFactory();
ef.export("蓝精灵");
}
}