1. 程式人生 > >java實現標準化考試系統詳解(二)-----資料庫、資料表的規劃和題庫增刪改查

java實現標準化考試系統詳解(二)-----資料庫、資料表的規劃和題庫增刪改查

(一)、資料庫、資料表的規劃

首先我們需要考慮一下作為考試系統我們需要哪些資料,這些資料將以後作為欄位值出現。

我們先來看看這張圖:


圖中框起來的部分基本上就是我們需要的資料,細數數就是:

1.試題序號,它作為主鍵出現不可以重複(id)

2.適用工程,可以理解為這個題適用於哪個學科(adaptEngineering)

3.難易度(complexity)

4.試題型別,用來區分是單選題還是多選題或者是判斷題(type)

5.試題內容(content)

6.圖片名稱,如果這道題帶圖片則需要錄入圖片名稱(pic)

7.選項A,B,C,D的內容(a,b,c,d)

8.正確答案(answer)

這張圖雖然體現的是選擇題資料,但是判斷題其實和它的資料差不多,我們可以讓判斷題的A,B選項內容始終為正確、錯誤,因此C,D兩個部分不填入內容即可,其他完全和選擇題相同。

(二)、具體實現:

1.建立資料庫並與其建立連線:

 Connection con;
 PreparedStatement ppStatement;
 String sql="";
//建立名為Examination的資料庫
 String url="jdbc:derby:Examination;create=true";
	try{
		
		con=DriverManager.getConnection(url);
		//建立名為Question的表
                sql ="create table Question"+
                "(id int primary key not null,"+
                "adaptEngineering varchar(20)," + 
                "complexity  varchar(20),"+
                "type  int,"+
                "content  varchar(500),"+
                "pic varchar(300),"+
                "a varchar(300),"+
                "b varchar(300),"+
                "c varchar(300),"+
                "d varchar(300),"+
                "answer varchar(20))";
        ppStatement=con.prepareStatement(sql);
        ppStatement.executeUpdate();
        con.close();
		
	}catch(SQLException exception)
	{
		System.out.println(exception);
	}

2.新增試題

   sql="insert into Question values(?,?,?,?,?,?,?,?,?,?,?)";
   id=Integer.valueOf(mView.mQuestionID.getText().trim());			
                ppStatement=con.prepareStatement(sql);
	        ppStatement.setInt(1,id); //向資料庫中寫入該題id
	        ppStatement.setString(2,mView.mApplicable.getText().trim());//寫入適用工程
	        ppStatement.setString(3, mView.mComplexityBox.getSelectedItem().toString());//複雜度
	        ppStatement.setInt(4,type);//試題型別
		ppStatement.setString(5,mView.mContext.getText().trim()); //試題內容
	        ppStatement.setString(6,mView.mPictureName.getText().trim()); //圖片名字(可為空,為空表示無圖)
	        ppStatement.setString(7,mView.inputA.getText().trim()); //a選項內容
	        ppStatement.setString(8,mView.inputB.getText().trim()); //b選項內容
	        ppStatement.setString(9,mView.inputC.getText().trim()); //c選項內容
	        ppStatement.setString(10,mView.inputD.getText().trim());//d選項內容
	        ppStatement.setString(11,mAnswer);//答案
	        isSucceed=ppStatement.executeUpdate();//提交資料
	        con.close();//關閉與資料庫連線

3.還需要一個工具類PreQuery類,他負責從資料庫中獲取欄位值和我們想要查詢的資料,我們可以通過他來檢視資料是否被插入到表中

public class PreQuery {
	String databaseName;//資料庫名稱
	String SQL;//需要執行的sql語句
	String[] columnName;//欄位值
	String[][] record;//讀取記錄儲存在二維陣列中
	Connection con;
	PreparedStatement preSql;
	ResultSet rs;//結果集
	public PreQuery(){
		try
		{
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
			
		}catch(Exception e)
		{
			System.out.println(e);
		}
	}
	public void setDatabaseName(String name)
	{
		databaseName=name.trim();
	}
	public void setSQL(String SQL)
	{
		this.SQL=SQL.trim();
	}
	public String[] getColumnName()
	{
		return columnName;
	}
	public String[][] getRecord()
	{
		return record;
	}
	public void startQuery()
	{

		try{
			String url="jdbc:derby:"+databaseName+" ;create=true";
			con=DriverManager.getConnection(url);
			//設定遊標可以隨意跳轉,這樣可以實現從任意一行讀取資料
			preSql=con.prepareStatement(SQL,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs=preSql.executeQuery();//將執行結果放入結果集
			ResultSetMetaData metaData=rs.getMetaData();
			int ziduanNum=metaData.getColumnCount();//得到欄位個數
			columnName=new String[ziduanNum];
			for(int i=1;i<=ziduanNum;i++)
			{
				columnName[i-1]=metaData.getColumnName(i);
			}
			rs.last();
			int dataNum=rs.getRow();//得到表中共有多少行記錄
			rs.beforeFirst();
			int i=0;
			record=new String[dataNum][ziduanNum];
			while(rs.next())
			{
				for(int j=1;j<=ziduanNum;j++)
				{
					record[i][j-1]=rs.getString(j);//讀取所有記錄
				}
				i++;
			}
			con.close();
		}catch(SQLException e)
		{
			System.out.println(e);
		}
	}
}

4.還需要一個具有表格的Dialog用來展示剛剛獲取到的資料

public class DialogOne extends JDialog {
   JTable table;
   String ziduan[];
   String record[][];
   public DialogOne() {
      setTitle("顯示記錄");
      setBounds(400,200,600,300);
      setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
   }
   public void setZiduan(String []ziduan){
      this.ziduan=ziduan;
   }
   public void setRecord(String [][]record){
      this.record=record;
   }
   public void init() {
       table = new JTable(record,ziduan);
       add(new JScrollPane(table));
   }
} 

5.選擇題管理檢視類AddAndUpdateChoiceQuestionView

public class AddAndUpdateChoiceQuestionView extends JPanel {
	   JTextField mQuestionID;     //輸入試題編號
	   JTextField mApplicable;     //適用工程
	   JTextArea  mContext;        //輸入試題內容
	   JTextField mPictureName;    //輸入圖片名字
	   JTextField inputA;          //輸入選擇a
	   JTextField inputB;          //輸入選擇b
	   JTextField inputC;          //輸入選擇c
	   JTextField inputD;          //輸入選擇d
	   JRadioButton[] mMultiselectBN;//多選題按鈕
	   JButton submitButton;          //提交按鈕
	   JComboBox<String> mOperate;//操作型別下拉選項
	   JComboBox<String> mType;//試題型別下拉選項
	   JComboBox<String> mAnswerBox;//答案選擇框
	   JComboBox<String> mComplexityBox;//難度選擇框
	   AddAndUpdateHandle handle;//該檢視的資料處理類
	   AddAndUpdateChoiceQuestionView()
	   {
		   setLayout(null);
		   setVisible(true);
		   submitButton=new JButton("提交");
		   mQuestionID=new JTextField(10);
		   mApplicable=new JTextField(10);
		   mContext=new JTextArea(8,40);	   
		   JScrollPane js=new JScrollPane(mContext);
		   mPictureName=new JTextField(10);
		   
		   
		   inputA=new JTextField(50);
		   inputB=new JTextField(50);
		   inputC=new JTextField(50);
		   inputD=new JTextField(50);
		   
		   JLabel mComboBoxJLabel=new JLabel("請選擇操作型別:");
		   mOperate=new JComboBox<String>();
		   mOperate.addItem("請選擇");
		   mOperate.addItem("新增試題");
		   mOperate.addItem("更新試題");
		   add(mComboBoxJLabel);
		   add(mOperate);
		   mComboBoxJLabel.setBounds(5, 85, 150, 35);
		   mOperate.setBounds(1, 115, 150, 35);

		   
		   JLabel mTypeLabel=new JLabel("請選試題型別:");
		   mType=new JComboBox<String>();
		   mType.addItem("請選擇");
		   mType.addItem("單項選擇");
		   mType.addItem("多項選擇");
		   add(mTypeLabel);
		   add(mType);
		   mTypeLabel.setBounds(5, 140, 150, 35);
		   mType.setBounds(1, 170, 150, 35);
		   

		   
		   JLabel mIdLabel =new JLabel("試題號:(必填且不允許重複)");
		   add(mIdLabel); 
		   add(mQuestionID);
		   mIdLabel.setBounds(5,5,165,35);
		   mQuestionID.setBounds(170,5,585,35);
		   
		   JLabel mApplicableLabel=new JLabel("適用工程:");
		   add(mApplicableLabel);
		   add(mApplicable);
		   mApplicableLabel.setBounds(5,415,150,35);
		   mApplicable.setBounds(155,415,600,35);
		   
		   JLabel mComplexityLabel=new JLabel("請選擇難易程度:");
		   mComplexityBox=new JComboBox<String>();
		   mComplexityBox.addItem("A");
		   mComplexityBox.addItem("B");
		   mComplexityBox.addItem("C");
		   mComplexityBox.addItem("D");
		   add(mComplexityLabel);
		   add(mComplexityBox);
		   mComplexityLabel.setBounds(320, 455, 150, 35);
		   mComplexityBox.setBounds(480, 455, 150, 35);
		   
		   JLabel mContextLabel=new JLabel("試題內容:");
		   add(mContextLabel);
		   add(js);
	       mContextLabel.setBounds(5,45,150,35);
	       js.setBounds(155,45,600,160);
		   
		   JLabel mPicNameLabel=new JLabel("圖片名稱:");
		   add(mPicNameLabel);
		   add(mPictureName);
		   mPicNameLabel.setBounds(5,210,150,35);
		   mPictureName.setBounds(155,210,600,35);
		     
		   
		   JLabel tishiA =new JLabel("選項A");
		   add(tishiA); 
		   add(inputA);
		   JLabel tishiB =new JLabel("選項B:");
		   add(tishiB); 
		   add(inputB);
		   JLabel tishiC =new JLabel("選項C:");
		   add(tishiC); 
		   add(inputC);
		   JLabel tishiD =new JLabel("選項D:");
		   add(tishiD); 
		   add(inputD);
		   
		   JLabel mAnswerLabel =new JLabel("請選擇單選題正確答案:");
		   mAnswerBox=new JComboBox<String>();
		   mAnswerBox.addItem("A");
		   mAnswerBox.addItem("B");
		   mAnswerBox.addItem("C");
		   mAnswerBox.addItem("D");
		   add(mAnswerLabel); 
		   add(mAnswerBox);
	           tishiA.setBounds(5,255,150,35);
	           inputA.setBounds(155,255,600,35);
	           tishiB.setBounds(5,295,150,35);
	           inputB.setBounds(155,295,600,35);
	           tishiC.setBounds(5,335,150,35);
	           inputC.setBounds(155,335,600,35);
	           tishiD.setBounds(5,375,150,35);
	           inputD.setBounds(155,375,600,35);
	           mAnswerLabel.setBounds(5, 455, 150, 35);
	           mAnswerBox.setBounds(155, 455, 150, 35);
		   
		   JLabel multiselectlJLabel=new JLabel("請選擇多選題答案:");
		   mMultiselectBN=new JRadioButton[4];
		   mMultiselectBN[0]=new JRadioButton("A");
		   mMultiselectBN[1]=new JRadioButton("B");
		   mMultiselectBN[2]=new JRadioButton("C");
		   mMultiselectBN[3]=new JRadioButton("D");
		   multiselectlJLabel.setBounds(5,500,150,35);
		   mMultiselectBN[0].setBounds(160, 500, 50, 35);
		   mMultiselectBN[1].setBounds(220, 500, 50, 35);
		   mMultiselectBN[2].setBounds(280, 500, 50, 35);
		   mMultiselectBN[3].setBounds(340, 500, 50, 35);
		   add(multiselectlJLabel);
		   for(int i=0;i<4;i++)
		   {
			   add(mMultiselectBN[i]);
		   }
	       
		   JLabel mButtonLabel=new JLabel("提交:");
		   add(mButtonLabel);
		   add(submitButton);
		   mButtonLabel.setBounds(5,540,150,35);
		   submitButton.setBounds(155,540,150,35);
		  	      
	      handle=new AddAndUpdateHandle();
	      handle.setView(this);
	      submitButton.addActionListener(handle);
	   }

}

6.這時候就可以實現選擇題管理類AddAndUpdateHandle類,他負責對AddAndUpdateChoiceQuestionView類的資料處理

public class AddAndUpdateHandle implements ActionListener{
  //所要監聽的檢視
   AddAndUpdateChoiceQuestionView mView;
   //連結資料庫所用工具
   Connection con;
   PreparedStatement ppStatement;
   PreQuery query;
   String sql="";
   String url="jdbc:derby:Examination;create=true";
   
   //寫入引數
   String OperateType;//操作型別
   String complexity;//複雜度
   String mAnswer;//答案
   int isSucceed;//判斷是否與資料庫建立連結
   int id;//試題號
   int type;//試題型別
   
   public AddAndUpdateHandle() {
	//資料庫連線預處理
	query=new PreQuery();
	try{
		
		con=DriverManager.getConnection(url);
		//建立名為Question的表
        sql ="create table Question"+
                "(id int primary key not null,"+
                "adaptEngineering varchar(20)," + 
                "complexity  varchar(20),"+
                "type  int,"+
                "content  varchar(500),"+
                "pic varchar(300),"+
                "a varchar(300),"+
                "b varchar(300),"+
                "c varchar(300),"+
                "d varchar(300),"+
                "answer varchar(20))";
        ppStatement=con.prepareStatement(sql);
        ppStatement.executeUpdate();
        con.close();
		
	}catch(SQLException exception)
	{
		System.out.println(exception);
	}
 }
   //設定所需要的檢視
   public void setView(AddAndUpdateChoiceQuestionView addAndUpdateChoiceQuestion)
   {
	   this.mView=addAndUpdateChoiceQuestion;
   }
   //點選提交按鈕響應
@Override
public void actionPerformed(ActionEvent e) {
	try{
		
		con=DriverManager.getConnection(url);
		OperateType=mView.mOperate.getSelectedItem().toString();
		sql="";
		//判斷操作型別
		if(OperateType.equals("新增試題"))
		{
			//使用預處理命令可以更靈活的設定各項的值
			sql="insert into Question values(?,?,?,?,?,?,?,?,?,?,?)";
			id=Integer.valueOf(mView.mQuestionID.getText().trim());
			//判斷試題型別
			if(mView.mType.getSelectedItem().toString().equals("單項選擇"))
			{
				//設定試題型別引數
				type=1;
				//得到使用者選擇的答案
				mAnswer=mView.mAnswerBox.getSelectedItem().toString();
			}else if(mView.mType.getSelectedItem().toString().equals("多項選擇"))
			{
				type=2;
				StringBuffer sb=new StringBuffer();
				for(int i=0;i<4;i++)
				{
					if(mView.mMultiselectBN[i].isSelected())
					{
						sb.append(mView.mMultiselectBN[i].getText().toString().trim());
					}
				}
				//得到多選題多個答案
				mAnswer=sb.toString();
			}
			ppStatement=con.prepareStatement(sql);
			ppStatement.setInt(1,id); //向資料庫中寫入該題id
			ppStatement.setString(2,mView.mApplicable.getText().trim());//寫入適用工程
			ppStatement.setString(3, mView.mComplexityBox.getSelectedItem().toString());//複雜度
		        ppStatement.setInt(4,type);//試題型別
		        ppStatement.setString(5,mView.mContext.getText().trim()); //試題內容
	                ppStatement.setString(6,mView.mPictureName.getText().trim()); //圖片名字(可為空,為空表示無圖)
	                ppStatement.setString(7,mView.inputA.getText().trim()); //a選項內容
	                ppStatement.setString(8,mView.inputB.getText().trim()); //b選項內容
	                ppStatement.setString(9,mView.inputC.getText().trim()); //c選項內容
	                ppStatement.setString(10,mView.inputD.getText().trim());//d選項內容
	                ppStatement.setString(11,mAnswer);//答案
	                isSucceed=ppStatement.executeUpdate();//提交資料
	                con.close();//關閉與資料庫連線
			
		}else if(OperateType.equals("更新試題"))
		{
			id=Integer.valueOf(mView.mQuestionID.getText().trim());
			sql="update Question set "	
					+ "adaptEngineering=?,"
					+ "complexity=?,"
					+ "type=?,"
					+ "content=?,"
					+"pic=?,"
					+"a=?,"
					+"b=?,"
					+"c=?,"
					+"d=?,"
					+"answer=? "
					+"where id ="
					+id;
			if(mView.mType.getSelectedItem().toString().equals("單項選擇"))
			{
				type=1;
				mAnswer=mView.mAnswerBox.getSelectedItem().toString();
			}else if(mView.mType.getSelectedItem().toString().equals("多項選擇"))
			{
				type=2;
				StringBuffer sb=new StringBuffer();
				for(int i=0;i<4;i++)
				{
					if(mView.mMultiselectBN[i].isSelected())
					{
						sb.append(mView.mMultiselectBN[i].getText().toString().trim());
					}
				}
				mAnswer=sb.toString();
			}else{
				//如果使用者未選擇操作型別則進行提示
				JOptionPane.showMessageDialog
		        (null,""+"請選擇試題型別!","訊息對話方塊", JOptionPane.WARNING_MESSAGE);
			}
			ppStatement=con.prepareStatement(sql);
			ppStatement.setString(1,mView.mApplicable.getText().trim());
			ppStatement.setString(2, mView.mComplexityBox.getSelectedItem().toString());
		        ppStatement.setInt(3,type);        
		        ppStatement.setString(4,mView.mContext.getText().trim()); 
	                ppStatement.setString(5,mView.mPictureName.getText().trim()); 
	                ppStatement.setString(6,mView.inputA.getText().trim()); 
	                ppStatement.setString(7,mView.inputB.getText().trim());
	                ppStatement.setString(8,mView.inputC.getText().trim()); 
	                ppStatement.setString(9,mView.inputD.getText().trim());
	                ppStatement.setString(10,mAnswer);
	                isSucceed=ppStatement.executeUpdate();
	                con.close();
		}else{
			JOptionPane.showMessageDialog
	        (null,""+"請選擇操作型別!","訊息對話方塊", JOptionPane.WARNING_MESSAGE);
		}
	}catch(SQLException exception)
	{
		//對資料庫操作失敗時彈出對話方塊進行提示
		JOptionPane.showMessageDialog
        (null,""+exception,"訊息對話方塊", JOptionPane.WARNING_MESSAGE);
	}
	//根據返回值可以判斷如果isSucceed=0則表示操作失敗,不為0表示操作成功
	if(isSucceed!=0)
	{
		//操作成功則對話方塊顯示剛剛插入或更新的資料
		query.setDatabaseName("Examination");
        query.setSQL("select * from Question where id="+id+"");
        query.startQuery();
        //得到欄位值
        String ziduan[] =query.getColumnName();
        //得到記錄
        String [][]record =query.getRecord();
        //對話方塊中顯示操作後的各項值
        DialogOne dialog = new DialogOne(); 
        dialog.setZiduan(ziduan);
        dialog.setRecord(record);
        dialog.init(); 
        dialog.setVisible(true);
      }
      else {
        JOptionPane.showMessageDialog
        (null,"新增試題失敗","訊息對話方塊", JOptionPane.WARNING_MESSAGE);
      }
}
   
}
增刪改查只是sql語句的不同其他並沒有什麼差異,判斷題的與選擇題類似因此我就不在這上面放程式碼了
原始碼下載網址(點開後面連結後在文章末尾有點選下載按鈕 原始碼下載備用連結:點選開啟連結

Java實現標準化考試系統詳解系類文章索引: