基于SQLite的信息管理系统

建立一个数据库,它可以方便地记录某个高速站口的人员信息。

一,代码逻辑

1,建立一个数据生产类Person;

2,建立一个SQLiteTool类,用来完成与数据库的链接;

3,建立一个可视化界面(GUI编程)类UIDesignDemo;

二,编写过程遇到的问题及解决思路

1,SQL语句错误:一是单词拼写错误,二是语法错误;

2,数据库找不到异常:解决办法是把数据库建立在同一个工程项目下;

3,数据记录错误:原因是把数据的顺序弄错了;

三,在工程项目中导入sqlite数据库

        这部分读者自己去查一下吧。

代码演示:

一:在同一个工程项目下建表

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/*
 * 这儿的代码只能运行一次,在这个工程项目下不能再执行这儿的代码
 * 表名为Person
 */
public class Demo_建表 {
	
		public static void main(String [] args) {
			Connection conn = null;
			Statement stmt = null;
			
			String sql = "CREATE TABLE PERSON"+"(ID  INT  PRIMARY KEY  NOT NULL,"
					+ "NAME  CHAR(50)  NOT NULL,"+"STARTPLACE  CHAR(50)  NOT NULL,"
					+"ENDPLACE  CHAR(50)  NOT NULL,"+"DATE  INT  NOT NULL)";
			
			try {
				Class.forName("org.sqlite.JDBC");
				conn = DriverManager.getConnection("jdbc:sqlite:Person.db");
				stmt = conn.createStatement();
				stmt.executeUpdate(sql);
				System.out.println("建表成功");
				conn.close();
			}catch(Exception e) {
				System.exit(0);
			}
		}
}

二:定义数据生产类

public class Person {
	    private int id;//为了防止数据溢出,身份证也使用日期的形式,如 20210312,长度不得超过8
	    private String name;
	    private String startPlace;
	    private String endPlace;
	    private int date;  //注意日期的写法格式为 20220112  代表2022年1月12日
	    public Person() {
	        id = 0;
	        name = " ";
	        startPlace = " ";
	        endPlace = " ";
	        date = 0;

	    }

	    public Person(int id, String name, String startPlace, String endPlace,int date) {
	        this.id = id;
	        this.name = name;
	        this.startPlace = startPlace;
	        this.endPlace = endPlace;
	        this.date = date;
	    }

	    public int getDate() {
	        return date;
	    }

	    public void setDate(int date) {
	        this.date = date;
	    }

	    public String getEndPlace() {
	        return endPlace;
	    }

	    public void setEndPlace(String endPlace) {
	        this.endPlace = endPlace;
	    }

	    public String getStartPlace() {
	        return startPlace;
	    }

	    public void setStartPlace(String startPlace) {
	        this.startPlace = startPlace;
	    }

	    public String getName() {
	        return name;
	    }

	    public void setName(String name) {
	        this.name = name;
	    }

	    public int getId() {
	        return id;
	    }

	    public void setId(int id) {
	        this.id = id;
	    }

}

三:链接数据库的工具类SQLiteTool类

import java.sql.*;

/*这儿我把自己遇到的问题都记录了下来
 * 问题:1,为什么建这个表只有在当前项目下才能被找到,如果把这个表健在其他项目下,就会发生“SQL error,not found table”异常???
 *     2,为什么查询结果打印出来的信息与建表的格式对不上,而且没有打印出名字???   查询结果:(0  20220322  贵阳  德江  20220322)
 *     3,为什么删除不了人员信息???
 *     
 *     问题2的原因:原来的insert方法中参数顺序设置错误,这儿是错误的顺序
 *               stmt.setString(1,person.getName());
                 stmt.setInt(2,person.getId());
 *
 *     问题3的原因:SQL语句错误
 * 
 */

public class SQLiteTool {
    private String driver = "org.sqlite.JDBC";
    private String name = "jdbc:sqlite:Person.db";

    private Connection conn = null;
    private PreparedStatement stmt = null;
 
    //链接数据库
    public  SQLiteTool(){
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(name);
            conn.setAutoCommit(false);//取消自动提交修改
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //增
    public boolean insert(Person person){
        boolean flag = false;
        String sql = "INSERT INTO Person VALUES(?,?,?,?,?)";
        try{
            stmt = conn.prepareStatement(sql);
            
            stmt.setInt(1,person.getId());
            stmt.setString(2,person.getName());
            stmt.setString(3,person.getStartPlace());
            stmt.setString(4,person.getEndPlace());
            stmt.setInt(5,person.getDate());

            if (stmt.executeUpdate()!=0){
                flag = true ;
                System.out.println("添加成功!");
            }
            stmt.close();
            conn.commit();//提交修改

        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    
    //模糊查询
    public void selectById(String name){ 
        ResultSet set = null;
        String sql = "SELECT*FROM Person WHERE NAME LIKE ?";

        try{
            stmt = conn.prepareStatement(sql);
            stmt.setString(1,"%"+name+"%"); // %可理解为任意字符 
            set = stmt.executeQuery();
            
            while(set.next()) {
            	
            	int result_1 = set.getInt("ID");
            	String result_2 = set.getString("NAME");
            	String result_3 = set.getString("STARTPLACE");
            	String result_4 = set.getString("ENDPLACE");
            	int result_5 = set.getInt("DATE");
            	
            	System.out.println(result_1+"  "+result_2+"  "+result_3+"  "+result_4+"  "+result_5);
            	
            }       
            set.close();
            conn.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //删
    public boolean deleteByID(int id) {
    	boolean flag = false;
    	String sql = "DELETE FROM Person WHERE ID LIKE ?";  
    	
    	try {
    		stmt = conn.prepareStatement(sql);
    		stmt.setInt(1,id);
    		
    		if(stmt.executeUpdate()!=0) {
    			flag = true;
    			System.out.println("成功删除身份证为"+id+"的人员信息!");
    		}
    		
    		stmt.close();
    		conn.commit();
    		
    	}catch(Exception e) {
    		System.out.println(e.getMessage());
    	}
    	
    	return flag;
    }
    	
    
}

四:UIDesignDemo类(GUI编程)

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class UIDesignDemo {
    JFrame frame;
    JPanel panel;
    JButton insertButton;
    JButton queryButton;
    JButton deleteButton;

    /*
        GUI编程中容易出现的bug有:
        1,组件无法显示,原因:组件必须先实例后再按主次添加,如先frame。add()然后是其他组件
        2,Swing和AWT组件不要混用,如,框架是Frame,但组件是JPanel或其他
        3.运行后会发现组件无法显示,要先点击一下最小化按钮再点开就可以了(这个原因与1的不同)
     */
    
    //main方法
    public static void main(String [] args) {
    	new UIDesignDemo();
    }

    public UIDesignDemo(){
    	SQLiteTool sqlitetool = new SQLiteTool();
        frame = new JFrame();
        frame.setSize(400,500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout(10,10));
        frame.setResizable(false);

        panel = new JPanel();
        panel.setLayout(null); //空白布局

        insertButton = new JButton("添加人员信息");
        insertButton.setBounds(80, 80, 200, 70);
        
        queryButton = new JButton("查询人员信息");
        queryButton.setBounds(80, 160, 200, 70);
        
        deleteButton = new JButton("删除人员信息");
        deleteButton.setBounds(80,240,200,70);
      
        JLabel label = new JLabel("疫情期间信息记录系统",JLabel.CENTER);
        label.setFont(new Font("楷体",Font.BOLD,20));

        frame.add(panel,BorderLayout.CENTER);
        frame.add(label, BorderLayout.NORTH);

        panel.add(insertButton);
        panel.add(queryButton);
        panel.add(deleteButton);

        //事件监听
        insertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new insertFrame();
            }
        });

        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new queryFrame();
            }
        });
        
       
       deleteButton.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent e) {
               new deleteFrame();
           }
       });
    }

}

class insertFrame {
    SQLiteTool sqliteTool;
    JFrame frame;
    JButton yesButton;
    JButton noButton;

    public insertFrame(){
        sqliteTool = new SQLiteTool();
        frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(400,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new BorderLayout());
        frame.setResizable(false);

        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BorderLayout());

        JPanel labelPanel = new JPanel();
        labelPanel.setLayout(new GridLayout(5,0,10,20));

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());

        JPanel fieldPanel = new JPanel();
        fieldPanel.setLayout(new GridLayout(5,0,10,20));

        JTextField  idText = new JTextField();
        JTextField  nameText = new JTextField();
        JTextField  startText = new JTextField();
        JTextField  endText = new JTextField();
        JTextField  dateText = new JTextField();

        JLabel label = new JLabel("请输入信息",JLabel.CENTER);
        label.setFont(new Font("楷体",Font.BOLD,20));

        JLabel idLabel = new JLabel("身份证");
        idLabel.setFont(new Font("楷体",Font.BOLD,20));

        JLabel nameLabel = new JLabel("姓名");
        nameLabel.setFont(new Font("楷体",Font.BOLD,20));

        JLabel startLabel = new JLabel("出发地");
        startLabel.setFont(new Font("楷体",Font.BOLD,20));

        JLabel endLabel = new JLabel("目的地");
        endLabel.setFont(new Font("楷体",Font.BOLD,20));

        JLabel dataLabel = new JLabel("日期");
        dataLabel.setFont(new Font("楷体",Font.BOLD,20));

        JButton yesButton = new JButton("确认");
        JButton noButton = new JButton("取消");

        frame.add(textPanel,BorderLayout.CENTER);
        frame.add(label,BorderLayout.NORTH);
        frame.add(buttonPanel,BorderLayout.SOUTH);

        buttonPanel.add(noButton);
        buttonPanel.add(yesButton);

        textPanel.add(labelPanel,BorderLayout.WEST);
        textPanel.add(fieldPanel,BorderLayout.CENTER);

        fieldPanel.add(idText);
        fieldPanel.add(nameText);
        fieldPanel.add(startText);
        fieldPanel.add(endText);
        fieldPanel.add(dateText);

        labelPanel.add(idLabel);
        labelPanel.add(nameLabel);
        labelPanel.add(startLabel );
        labelPanel.add(endLabel);
        labelPanel.add(dataLabel);

        yesButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sqliteTool.insert(new Person(
                        Integer.parseInt(idText.getText()),nameText.getText(),startText.getText(),
                        endText.getText(),Integer.parseInt(dateText.getText())));

            }
        });

        noButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
            }
        });

    }

}

class queryFrame {

    SQLiteTool sqliteTool;
    JFrame frame;

    public queryFrame(){
         sqliteTool = new SQLiteTool();
         frame = new JFrame();
	     frame.setVisible(true);
	     frame.setSize(400,300);
	     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	     frame.setLayout(new BorderLayout());
	     frame.setLocationRelativeTo(null);
	     frame.setResizable(false);

	     JLabel label = new JLabel("请输入要查询人的全名或名字含有的字",JLabel.CENTER);
	     label.setFont(new Font("楷体",Font.BOLD,20));
	        
	     JLabel idLabel = new JLabel("姓名");
	     idLabel.setFont(new Font("楷体",Font.BOLD,20));
	        
	     JPanel panel_1 = new JPanel();
	     panel_1.setLayout(new GridLayout(5,0,10,10));
	      
	     JPanel panel_2 = new JPanel();
	     panel_2.setLayout(new GridLayout(5,0,10,10));
	        
	     JPanel panel_3 = new JPanel();
	     panel_3.setLayout(new GridLayout(1,2,10,10));
	        
	     JTextField text = new JTextField();
	        
	        
	     JButton  yesButton = new JButton("确认");
	     JButton  noButton = new JButton("取消");
	     
	     yesButton.addActionListener(new ActionListener() {
	    	 public void actionPerformed(ActionEvent e) {
	    		 sqliteTool.selectById(text.getText());
	    	 }
	     });
	     
	     noButton.addActionListener(new ActionListener() {
	    	 public void actionPerformed(ActionEvent e) {
	    		 frame.setVisible(false);
	    	 }
	     });
	        

	        frame.add(label,BorderLayout.NORTH);
	        frame.add(panel_1,BorderLayout.WEST);
	        frame.add(panel_2,BorderLayout.CENTER);
	        frame.add(panel_3,BorderLayout.SOUTH);
	       
	        panel_1.add(idLabel);
	        
	        panel_2.add(text);
	        
	        panel_3.add(yesButton);
	        panel_3.add(noButton);
	        
    }
}

class deleteFrame{
	
	SQLiteTool sqliteTool;
	JFrame frame;
	
	public deleteFrame() {
		 SQLiteTool sqliteTool = new SQLiteTool();
		 frame = new JFrame();
	     frame.setVisible(true);
	     frame.setSize(400,300);
	     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	     frame.setLayout(new BorderLayout());
	     frame.setLocationRelativeTo(null);
	     frame.setResizable(false);

	     JLabel label = new JLabel("请输入要删除的人的身份证号",JLabel.CENTER);
	     label.setFont(new Font("楷体",Font.BOLD,20));
	        
	     JLabel idLabel = new JLabel("身份证");
	     idLabel.setFont(new Font("楷体",Font.BOLD,20));
	        
	     JPanel panel_1 = new JPanel();
	     panel_1.setLayout(new GridLayout(5,0,10,10));
	      
	     JPanel panel_2 = new JPanel();
	     panel_2.setLayout(new GridLayout(5,0,10,10));
	        
	     JPanel panel_3 = new JPanel();
	     panel_3.setLayout(new GridLayout(1,2,10,10));
	        
	     JTextField text = new JTextField();
	       
	     JButton  yesButton = new JButton("确认");
	     JButton  noButton = new JButton("取消");
	     
	     yesButton.addActionListener(new ActionListener() {
	    	 public void actionPerformed(ActionEvent e) {
	    		 sqliteTool.deleteByID(Integer.parseInt(text.getText()));
	    	 }
	     });
	     
	     noButton.addActionListener(new ActionListener() {
	    	 public void actionPerformed(ActionEvent e) {
	    		 frame.setVisible(false);
	    	 }
	     });
	        
	        frame.add(label,BorderLayout.NORTH);
	        frame.add(panel_1,BorderLayout.WEST);
	        frame.add(panel_2,BorderLayout.CENTER);
	        frame.add(panel_3,BorderLayout.SOUTH);
	       
	        panel_1.add(idLabel);
	        
	        panel_2.add(text);
	        
	        panel_3.add(yesButton);
	        panel_3.add(noButton);
		
	}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,Python基于SQLite的通讯录管理系统可以分为以下几个模块: 1. 数据库模块:使用SQLite数据库存储联系人信息,提供增删改查接口。 2. 用户界面模块:提供图形用户界面,包括添加联系人、删除联系人、修改联系人、查询联系人等操作。 3. 数据处理模块:将用户界面的操作转化为数据库操作,处理数据库返回的结果并展示给用户。 下面是一个简单的实现代码: ```python # 导入SQLite模块 import sqlite3 # 定义数据库文件名 DB_FILE = 'contacts.db' # 连接数据库 def connect_db(): conn = sqlite3.connect(DB_FILE) return conn # 创建联系人表 def create_table(conn): cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone TEXT, email TEXT)''') conn.commit() # 添加联系人 def add_contact(conn, name, phone, email): cursor = conn.cursor() cursor.execute('INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)', (name, phone, email)) conn.commit() # 删除联系人 def delete_contact(conn, id): cursor = conn.cursor() cursor.execute('DELETE FROM contacts WHERE id = ?', (id,)) conn.commit() # 修改联系人 def update_contact(conn, id, name, phone, email): cursor = conn.cursor() cursor.execute('UPDATE contacts SET name = ?, phone = ?, email = ? WHERE id = ?', (name, phone, email, id)) conn.commit() # 查询联系人 def query_contact(conn, name): cursor = conn.cursor() cursor.execute('SELECT id, name, phone, email FROM contacts WHERE name like ?', ('%' + name + '%',)) return cursor.fetchall() # 用户界面 def main(): conn = connect_db() create_table(conn) while True: print('1. 添加联系人') print('2. 删除联系人') print('3. 修改联系人') print('4. 查询联系人') print('5. 退出程序') choice = input('请输入选项: ') if choice == '1': name = input('请输入姓名: ') phone = input('请输入电话: ') email = input('请输入邮箱: ') add_contact(conn, name, phone, email) elif choice == '2': id = input('请输入要删除的联系人id: ') delete_contact(conn, id) elif choice == '3': id = input('请输入要修改的联系人id: ') name = input('请输入新的姓名: ') phone = input('请输入新的电话: ') email = input('请输入新的邮箱: ') update_contact(conn, id, name, phone, email) elif choice == '4': name = input('请输入要查询的联系人姓名: ') contacts = query_contact(conn, name) for contact in contacts: print(contact) elif choice == '5': break else: print('输入错误,请重新输入!') conn.close() if __name__ == '__main__': main() ``` 这段代码中,我们首先定义了一个`DB_FILE`常量,作为SQLite数据库文件名,然后定义了一些数据库操作函数,如`connect_db()`、`create_table()`、`add_contact()`、`delete_contact()`、`update_contact()`、`query_contact()`等。最后,在`main()`函数中,我们通过输入输出实现了一个简单的用户界面,将用户输入的操作转化为相应的数据库操作,并将处理结果展示给用户。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Gloaming@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值