JAVA编程实现郑码查询(2)——将码表放在mysql数据库中

  1. 打开小小输入法的郑码表观察,如
    a 一 再
    aa 一下
    aaam 万无一失
    aaav 可歌可泣
    aaax 天下无难事
    aacf 百无聊赖
    aacm 无可奉告
    aadj 无可挽回
    aadt 殊死搏斗
    aaeu 平型关
    aaez 一开始
    。。。
    编程实现一个命令窗程序,使得能进行郑码查询,如输入aacm,则输出“无可奉告”。(方法:将码表放在一个mysql数据库中。)

将郑码表放在mysql数据库中:
这里写图片描述
如下显示可以在MySQL中查询郑码表
这里写图片描述
JAVA实现郑码查询,代码如下:

import java.sql.*;       
import java.util.Scanner;

class MySQLZMB {
    static Connection con;   
    static Statement sql;      
    static ResultSet res;     
    public Connection getConnection(){   
        try {                              //加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        try {               
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/zmdb","root","");//连接数据库(url,用户名root,密码为空)
            System.out.println("Succeeded connecting to the Database!");
            System.out.print('\n');
        }catch(SQLException e) {
            e.printStackTrace();
        }
        return con; 
    }
    public static void main(String[] args){  //主程序
        Scanner scan = new Scanner(System.in);
        MySQLZMB c = new MySQLZMB();       
        con =c.getConnection();              //与数据库建立连接
        while(true) {
            try {
                sql = con.createStatement();     //操作数据库
                res = sql.executeQuery("select * from zmb");//要执行的语句
                    String str = scan.nextLine();    
                    boolean b = false;         //判断字典中是否含有输入的词            
                    while(res.next()) {      
                        String en = res.getString("english");      //获取english字段值
                        String ch = res.getString("chinese");      //获取chinese字段值
                        String english = en.substring(en.indexOf("<")+1,en.indexOf(">"));  //返回指数在这个字符串指定的子字符串中第一个出现的下标
                        String chinese = ch.substring(ch.lastIndexOf("<")+1,ch.lastIndexOf(">")); //返回指数在这个字符串的指定子字符串中最后出现的下标
                        if(str.equals(english)) { //对应英文的该词存在
                            System.out.println(chinese);
                            b = true;             
                        }
                        if(str.equals(chinese)) {  //对应中文的该词存在
                            System.out.println(english);
                            b = true;             
                        }
                    }
                    if(str.equals("ByeBye")) //判断是否输入的为ByeBye
                    {     
                        System.exit(0);//退出程序
                    }
                    if(!b) {                  //查找不到对应的词    
                        System.out.println("查不到该词");    
                    }
             }catch(SQLException e) {
                    e.printStackTrace();
             }
       }
    }
}

运行过程如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42014622/article/details/80371101