2014年复试数据库上机之数据库连接+导出数据到文件中

 1 package scut.film;
 2 
 3 import java.io.File;
 4 import java.io.FileWriter;
 5 import java.io.PrintWriter;
 6 import java.sql.Connection;
 7 import java.sql.DriverManager;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.sql.Statement;
11 
12 public class SCUTFILM {
13   
14 //-----------------------------------------------------------------数据库连接部分
15     public static void main(String[] args) throws SQLException, ClassNotFoundException {
16         Connection conn = null;
17         Statement stmt = null;
18         ResultSet rs = null;
19         try {
20             String data ="jdbc:sqlserver://localhost:1433;databaseName=SCUT_FILM";
21             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
22             conn = DriverManager.getConnection(data ,"qjy","qjy");
23             stmt = conn.createStatement();
24         }catch (SQLException ex) {
25             System.out.println("SQLException: " + ex.getMessage());
26             System.out.println("SQLState: "     + ex.getSQLState());
27             System.out.println("VendorError: "  + ex.getErrorCode());
28         }
29   // -------------------------------------------------------------------查询部分
30         try {
31 
32             rs = stmt.executeQuery("select * from 放映厅表");
33             System.out.println("执行结果如下所示:");
34             while (rs.next()) {
35                 String sno   = rs.getString("放映厅号");
36                 String sname = rs.getString("放映厅名");
37                 String sseat = rs.getString("座位数");
38                 newFile("E:\\查询结果.txt",sno+"   "+sname+"   "+sseat);
39                 System.out.println( sno + "\t" + sname + "\t" + sseat);
40             }
41             rs.close();
42             conn.close();
43 
44         }catch (Exception e) {
45             e.printStackTrace();
46         }
47     }
48 //----------------------------------------------------------------------文件部分
49     public static void newFile(String filePathAndName, String fileContent) {
50         try {
51 
52             File myFilePath = new File(filePathAndName);
53             if (!myFilePath.exists()) {
54                 myFilePath.createNewFile();
55             }
56 
57             FileWriter resultFile = new FileWriter(myFilePath, true);
58             PrintWriter myFile = new PrintWriter(resultFile);
59             myFile.println(fileContent);  
60             resultFile.close();
61         } catch (Exception e) {
62             e.printStackTrace();
63         }
64     }
65 }

 

posted @ 2016-03-27 17:01  chynn-SE  阅读(149)  评论(0)    收藏  举报