|
Tips & Tricks |
|
This is the program below, which will copy the
above data to the MySQL.
ExcelToMySQL.java
import java.sql.*;
import java.util.*;
import java.io.*;
public class ExcelToMySQL {
public static void main(String args[]) throws
IOException{
System.out.println(“Enter table name:”);
BufferedReader bf = new
BufferedReader(new
InputStreamReader(System.in));
String tableName = bf.readLine();
Connection con_excel = null, con_mysql =
null;
Statement stmt_excel = null, stmt_mysql
= null;
ResultSet rs_excel = null;
List columnNameList = null;
try {
con_excel =
getConnection(“sun.jdbc.odbc.JdbcOdbcDriver”,
“jdbc:odbc:myexcel”, “”, “”);
stmt_excel =
con_excel.createStatement();
String query_excel = “select * from
[Sheet1$]”;
rs_excel =
stmt_excel.executeQuery(query_excel);
columnNameList =
getColumnNameList(rs_excel);
|
|
con_mysql =
getConnection(“com.mysql.jdbc.Driver”,
“jdbc:mysql://localhost:3306/test”, “root”,
“root”);
stmt_mysql =
con_mysql.createStatement();
String query_mysql =
getQueryStringToCreateTable(tableName,
columnNameList);
stmt_mysql.executeUpdate(query_mysql);
PreparedStatement p_stmt_mysql =
con_mysql.prepareStatement
(getQueryStringToInsertValues(tableName,
columnNameList));
insertValuesAndExecuteQuery
(rs_excel,columnNameList,p_stmt_mysql);
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
try {
rs_excel.close();
stmt_excel.close();
stmt_mysql.close();
con_excel.close();
con_mysql.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
public static Connection
getConnection(String driver, String url, String
username, String password) throws
Exception {
Class.forName(driver);
return DriverManager.getConnection(url,
username, password);
}
public static List
getColumnNameList(ResultSet rs) throws
SQLException{
List list = new ArrayList();
ResultSetMetaData rsmd =
rs.getMetaData();
int numberOfColumns =
rsmd.getColumnCount();
for (int i = 1; i < numberOfColumns + 1;
i++) {
|
|
|
Feb 2008 | Java Jazz Up | 67 |
|
|
View All Topics |
All Pages of this Issue |
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63 ,
64,
65 ,
66 ,
67 ,
68 ,
69 ,
70 ,
71 ,
72 ,
Download PDF |
|
|
|
|
|
|
|
|