A simple formatting letter Generator

Source: Internet
Author: User

Kids shoes should have seen a variety of invitations, usually a template above, and then fill in the invitee and related information, which is called the "mail merge" feature in word. Today, we will implement a simple formatting letter generator. What we will do, including a very simple database for selecting course students, and a simple template, which uses the records and templates in the database to generate formatted notification information. For the implementation of C language, see section 2 of chapter 3 in programming pearl I (version 2.

Don't look at this simple thing, it also contains the unchanged and changing part. Unchanged is the Information Template content, and the change part is the record information in the database. All you need to do is to isolate the change from the change. The basic design philosophy is as follows:

1. A very simple database for selecting students, including students, courses, and stus_cours;

2. a jdbc Utility Class, jdbcutil, mainly retrieves records from the database and converts them into corresponding record objects dbrecord;

3. Record object dbrecord: contains a string [] array to store data items in each record. A string corresponds to a basic data item.

4. template information interface: Interface Template, which contains a gettext () method declaration;

5. Implementation of two templates: course opening information courseinfotemplate and course selection information coursechosentemplate

6. Formatting letter generator formattedletter: generates formatting notifications based on database records and templates.

Because this is not complicated, I will not explain it too much here. I believe that the children's shoes will soon understand the code. The following code is implemented:

### Course. SQL

######################################## ####### Course. SQL: create a simple database for student course selection # Note: The database must be saved in UTF-8 format (file-Save ), # To ensure that the file can be smoothly inserted into the Chinese language ########################## ######################################## ########################### how to Exec SQL file # mysql-u root-P </your_path/course. SQL # Enter password: [input your Root Password] ################################## ########### or use root to log on to MySQL, # Copy all statements and execute them in MySQL. ######################################## ######################################## #### MySQL statement: ###################################### create user 'course6' @ 'localhost' identified by 'course6 '; create Database course; grant all on course. * To 'course6' @ 'localhost '; ##################################### use course; create Table students (ID int not null auto_increment, stuname varchar (12) not null, primary key (ID); Create Table courses (ID int not null auto_increment, cname varchar (15) not null, ctime int not null, note varchar (30), primary key (ID); Create Table stus_cours (stu_id int not null, cour_id int not null, sch_term varchar (5) not null, primary key (stu_id, cour_id); alter table stus_cours add constraint stucons foreign key (stu_id) References students (ID); alter table stus_cours add constraint courcons foreign key (cour_id) references courses (ID); DESC courses; DESC students; DESC stus_cours; insert into students values (10001, 'hua '); insert into students values (10002, 'James '); insert into courses values (1001, 'high number', 54, ''); insert into courses values (1002, 'College English ', 81 ,''); insert into stus_cours values (10001,100 1, '2nd '); insert into stus_cours values (10002,100 1, '2nd'); insert into stus_cours values (10001,100 2, '1st '); insert into stus_cours values (10002,100 2, '1st'); select * from students; select * from courses; select * From stus_cours; select stuname, cname, ctime, sch_term from students, courses, stus_cours where students. id = stus_cours.stu_id and courses. id = stus_cours.cour_id;

Jdbcutil. Java

package javatech.JDBClearn;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.mysql.jdbc.ResultSetMetaData;import com.mysql.jdbc.Statement;public class JDBCUtil {private static Connection conn;private static final String mysqlDriver = "com.mysql.jdbc.Driver";private static final String mysqlURL = "jdbc:mysql://localhost:3306/course";private static final String username = "course6";private static final String password = "course6";private JDBCUtil() { }public static Connection getConnection() throws SQLException, ClassNotFoundException {Class.forName(mysqlDriver);conn = DriverManager.getConnection(mysqlURL, username, password);return conn;}public static void printResult(ResultSet rs) throws SQLException{ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();int colNum = rsmd.getColumnCount();while(rs.next()) {for (int i = 0; i < colNum; i++)                 System.out.printf(rs.getString(i+1) + " ");System.out.println();}}public static List<DBRecord> toRecords(ResultSet rs) throws SQLException {List<DBRecord> records = new ArrayList<DBRecord>();ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();int colNum = rsmd.getColumnCount();while(rs.next()) {String[] datas = new String[colNum];for (int i = 0; i < colNum; i++)                 datas[i] = rs.getString(i+1);records.add(new DBRecord(datas));}rs.close();conn.close();return records;}public static ResultSet getResultSet(String sqlString) throws SQLException, ClassNotFoundException{Connection conn = getConnection();Statement stm = (Statement) conn.createStatement();ResultSet rs = stm.executeQuery(sqlString);return rs;}public static void main(String[] args) throws SQLException, ClassNotFoundException{String sqlString = "SELECT stuName, cName, cTime, sch_term " +                           "FROM students, courses, stus_cours " +                           "WHERE students.id = stu_id AND " +                           "      courses.id = cour_id; ";ResultSet rs = getResultSet(sqlString);printResult(rs);rs.close();conn.close();}}

Dbrecord. Java

Package javatech. jdbclearn;/*** dbrecord: the data object corresponding to a row record in the database **/public class dbrecord {// converts a record retrieved in the database into a string and stores the private string [] datas; public dbrecord (string [] datas) {This. datas = datas;} // returns the first index data item of a record in the database. Public String getdataterm (INT index) {If (index <0 | index> datas. length-1) {Throw new arrayindexoutofboundsexception ("array subscript out of bounds! ");} Return datas [Index];} // return the number of data items contained in a record of the database. Public int datatermnum () {return datas. length;} Public String tostring () {stringbuilder sb = new stringbuilder ("[dbrecord]:"); For (string S: datas) {sb. append (s); sb. append ('');} sb. append ('\ n'); return sb. tostring ();}}

Formattedletter. Java

Package javatech. jdbclearn; import Java. SQL. resultset; import Java. SQL. sqlexception; import Java. util. arraylist; import Java. util. list; public class formattedletter {/*** replaces the template data in the template with the data items recorded in the database in sequence. * @ Param record * @ Param TPL specifies the interface of the template file * @ return format letter after replacement */Public String formattedletter (dbrecord record, template TPL) {string text = TPL. gettext (); For (INT I = 0; I <record. datatermnum (); I ++) TEXT = text. replaceall ("\ $" + (I + 1), record. getdataterm (I); return text;}/*** generate multiple formatting letters */public list <string> batformattedletter (list <dbrecord> records, template TPL) {list <string> letters = new arraylist <string> (); For (dbrecord R: records) {letters. add (formattedletter (R, TPL);} return letters;}/*** printlist: print the list content */public static <t> void printlist (list <t> List) {system. out. println ("list: ["); For (T: List) {system. out. println (t);} system. out. println ("]");} public static void test (string sqlstmt, template TPL) throws sqlexception, classnotfoundexception {resultset rs = jdbcutil. getresultset (sqlstmt); List <dbrecord> records = jdbcutil. torecords (RS); List <string> letters = new formattedletter (). batformattedletter (records, TPL); system. out. println ("formatted letters:"); printlist (letters);} public static void main (string [] ARGs) throws sqlexception, classnotfoundexception {string courseinfosql = "select cname, ctime from courses "; test (courseinfosql, new courseinfotemplate (); string coursechosenstring =" select stuname, cname, ctime, sch_term "+" from students, courses, stus_cours "+" where students. id = stu_id and "+" courses. id = cour_id; "; test (coursechosenstring, new coursechosentemplate ());}}

Courseinfotemplate. Java

Package javatech. jdbclearn; public class courseinfotemplate implements template {private string text = "students note: this semester offers $1 courses for $2 hours. Do not miss this course! "; Public String gettext () {return text ;}}

Coursechosentemplate. Java

Package javatech. jdbclearn; public class coursechosentemplate implements template {private string text = "$1, hello! The course you take is $2 for $3 hours. Do not miss it on $4. "; Public String gettext () {return text ;}}

Template. Java

package javatech.JDBClearn;public interface Template {String getText();}

Note: What can be improved

1. Using the replaceall method to replace multiple templates in the template file may be inefficient and needs to be improved;

2. You must replace the data items retrieved from the database and the template items defined in the template in sequence, rather than unordered replacement;

3. the template file and the formatting letter generator can also be more flexible. For example, you can add an input and output stream so that the template file can come from various input streams rather than simple strings, formatting information can be output to various target streams, not just the console.
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.