//读取数据
package com.gupiao.views;import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 抓取网络数据的类
 * 数据位 : 日期、开、高、收、低、交易量(交易金额)
 * @author Administrator
 *
 */
public class StockDataMining {      private static String myStr="http://biz.finance.sina.com.cn/stock/flash_hq/kline_data.php?";
/*完整链接如:http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/" +
"600006.phtml?year=2013&jidu=4";*/
      static int c;
//      static String wj=c+".txt";
      static String mdate;
public static void main(String[] args){
StockDataMining sd=new StockDataMining();
try {
sd.gPselt("20170106", "20160101");
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
/**
* 根据url从新浪财经上获取股票数据
* @param   
* @param code  股票代码
* @param year  年份
* @param jidu  季度(1、2、3、4)
* @return  null,如果异常发生。否则返回一个arraylist ,其中每个元素为一个hashmap———里面的值从1~7分别为 :日期、开、高、收、低、交易量、交易金额
* @throws MalformedURLException 
*/
public HashMap<Integer, Object> getStockData(String Str,String code,String enddate,String begindate){
try { //拼接完整url
    String tempStr=myStr+Str+code+"&end_date="+enddate+"&begin_date="+begindate+"&type=plain";
    URL  url=new URL(tempStr);
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            
///创建输入流
    BufferedReader reader = null;
    reader=new BufferedReader(new InputStreamReader(url.openStream()));
//创建hashmap存储每一行具体数据
    HashMap<Integer, Object> hashMap=new HashMap<Integer, Object>();
///匹配读取内容,并存入list里面
    int i=0;
    String str;
    Cb cb=new Cb();
//     cb.Mdate(code);
//     mdate=Cb.gpDatem;
    System.out.printf(code+"");
    while((str=reader.readLine())!= null){
     System.out.println(str);
        for(String s :str.trim().split(",")){         
         hashMap.put(Integer.valueOf(i),s);
         System.out.println(hashMap.get(i));
         i++;
         System.out.println(i);
        }
         
//         String fileName ="D:"+File.separator+"hk"+File.separator+"gupsj"+File.separator+code+".txt";
//         File f=new File(fileName);
//         Writer out = new FileWriter(f,true);
//         out.write(matcher.group()+" ");
//         if(7==i){
//          out.write("\r\n");
//          }
//         out.close();
///左对齐输出
//System.out.printf("%-22s", matcher.group());
    if(i>=6){
     cb.Date(code,hashMap,"2017-01-19 00:00:00.0");
     System.out.printf("进入数据库11111");
//      System.out.println(hashMap.get(1)+"  "+hashMap.get(2)+"  "+hashMap.get(3)+"  "+hashMap.get(5)+" "
// + " "+hashMap.get(4)+"  "+hashMap.get(6)+"  "+hashMap.get(7)+"\r\n");
//每七个数据算一行,此时把该行数据存入list并且重置i,与hashMap
     i=0;
     hashMap=new HashMap<Integer, Object>();
     } 
    }//end of while
    return hashMap;
    } catch (IOException e) {
// TODO Auto-generated catch block
     e.printStackTrace();
     } 
return null;
}public void gPselt(String a,String b) throws IOException{
for(int n=10;n<1000;n++){
String str="&rand=random(10000)&symbol=sz";
// c=n;
System.out.println(n);
if(n<10){
// File fl=new File("D:/hk/gupsj/"+"00000"+wj);
// fl.createNewFile();
this.getStockData(str,"00000"+n, a, b);
}
 if(n>=10&&n<100){
// File fl=new File("D:/hk/gupsj/"+"0000"+wj);
// fl.createNewFile();
this.getStockData(str,"0000"+n, a, b);
}else if(n>=100&&n<1000){
// File fl=new File("D:/hk/gupsj/"+"000"+wj);
// fl.createNewFile();
this.getStockData(str,"000"+n, a, b);
}
for(int m=600001;m<602000;m++){
// c=m;
System.out.println(m);
// File fl=new File("D:/hk/gupsj/"+wj);
// fl.createNewFile();
    String tr="&rand=random(10000)&symbol=sh";
this.getStockData(tr,m+"", a, b);
}
for(int m=603000;m<604000;m++){
// c=m;
System.out.println(m);
// File fl=new File("D:/hk/gupsj/"+wj);
// fl.createNewFile();
    String trc="&rand=random(10000)&symbol=sh";
this.getStockData(trc,m+"", a, b);
}
}
}
}//连接数据库
package com.gupiao.views;import java.sql.*;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;public class Cb { static String gpDatem;
PreparedStatement ps=null;
Connection ct=null;
ResultSet rs=null;
String st1=null;
String st2=null;
String st3=null;
String st4=null;
String id=null;//获取最近日期
public void Mdate(String tablename){
    this.Update();
// System.out.println("进入MDATE");
st4="select * from ngp"+tablename+" where gpDate=(select Max(gpDate) from ngp"+tablename+")";
try {
ps = ct.prepareStatement(st4);
// System.out.println("11111");
rs = ps.executeQuery();
System.out.println("读取数据");
while (rs.next()) {
id = rs.getString("gpid");
gpDatem = rs.getString("gpDate");
System.out.println(id + " " + gpDatem);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
try {
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (ct != null)
ct.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}


}

//根据接收到的数据输入数据库
public void Date(String tablename,HashMap<Integer, Object> hashMap,String j){
this.Update();
System.out.println("ok-----");
try {
//         st1="create table "+"gp"+tablename+"(gpid nvarchar(50),gpDate datetime,gpOpen nvarchar(50),"
// + "gpHigh nvarchar(50),gpLow nvarchar(50),gpClose nvarchar(50),gpVolume nvarchar(50),"
// + "gpAmount nvarchar(50))";
st2="insert into "+"ngp"+tablename+" (gpid,gpDate,gpOpen,gpHigh,gpLow,gpClose,gpVolume)"+" values ('"+tablename+"','"+hashMap.get(0)+"','"+hashMap.get(1)+"','"
                    +hashMap.get(2)+"','"+hashMap.get(4)+"',"+ "'"+hashMap.get(3)+"','"+hashMap.get(5)+"')";
// Bijiao bj=new Bijiao();
// String newdate=hashMap.get(0).toString()+" 00:00:00.0";
// try {
// switch(bj.timeBijiao(newdate,gpDatem)){
// case 1:
        System.out.println("ok+++++");
ps=ct.prepareStatement(st2);
int t2=ps.executeUpdate();
System.out.println("ok");
// case 0:
// break;
// default:
// break;
// }
// } catch (ParseException e) {
// // TODO 自动生成的 catch 块
// e.printStackTrace();
// }
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{

}
} //连接数据库
public void Update(){
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//加载数据库引擎,返回给定字符串名的类
}catch(ClassNotFoundException e)
{
//e.printStackTrace();
System.out.println("加载数据库引擎失败");
System.exit(0);

try
{
String URL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=ngp";
String user="sa";
String password="123456";
ct=DriverManager.getConnection(URL,user,password);//连接数据库对象
System.out.println("连接数据库成功");
}
catch (Exception e){
e.printStackTrace();
}finally{

}

}
}