哈工大 java实验5 数据库程序设计

这次试验涉及数据库的一些操作,大概用到如下几个命令。

新建一个数据库

create database phplampDB;

创建一个表                          TYPE=MyISAM是指该表使用MyISAM存储引擎,不写也行,主键要设成username           创建student的表类似。

CREATE TABLE `admin` ( 
`username` varchar(20) NOT NULL, 
`passwd` varchar(20) NOT NULL, 
PRIMARY KEY (`username`) 
) TYPE=MyISAM;


查询表中的记录

select * from table;

插入一条记录       into 不写也行

insert into admin values(“tom”,”123”);

查看mySQL所使用的端口       写程序的时候要用到,不过一般都是默认的。

show variables like 'port';

最后提醒一下MySQL里的数据都可以用用双引号引起来,字段名什么的可以用键盘上1左边tab上边的那个键引起来,很容易弄混。


接下来就可以开始写程序了,连接数据库需要一个叫做mysql-connector-java的包,下好后把它加入工程,我是用Add External JARs简单的加进去的,其实也可以设置环境变量。连接数据库需要这样写。

try{
			Class.forName(driver);
			conn=DriverManager.getConnection(url,user,pass);
			if (!conn.isClosed()){
				System.out.println("Success");
				statement = conn.createStatement();
				rs = statement.executeQuery("select * from admin");
			}
		}catch(Exception e){
			System.out.println("exception");
		}
变量如下:

	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://127.0.0.1:3306/hit";
	private static String user="root";
	private static String pass="nihaoa";
	private static Connection conn;
	private static ResultSet rs;
	private static Statement statement;

Class.forName()静态方法是为了动态加载类,一般在加载完成后还需要调用newInstance()来实例化对象,其实它和new差不多,不过newInstance()只支持无参数初始化。

Class.forName("")返回一个类 
Class.forName("").newInstance()返回一个object 

刚才提到,Class.forName("");的作用是要求JVM查找并加载指定的类,如果在类中有静态初始化器的话,JVM必然会
执行该类的静态代码 段。而在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,即任何一个JDBC 
Driver的 Driver类的代码都必须类似如下:
  public class MyJDBCDriver implements Driver {
   static {
     DriverManager.registerDriver(new MyJDBCDriver());
  }
  }
 既然在静态初始化器的中已经进行了注册,所以我们在使用JDBC时只需要Class.forName(XXX.XXX);就可以了。


布局都很熟了就不多说了

工具栏我是这样写的

private void installTollBar(){
			toolBar = new JToolBar();
			button1.addActionListener(this);
			button2.addActionListener(this);
			toolBar.add(button1);
			toolBar.add(button2);
			add(toolBar,BorderLayout.NORTH);
		}

table是这样   这里要注意一点最好把table加在一个其他的pane(JScrollPane最好),不然有可能出现显示不出字段名的情况。

private void installTable(){
			table = new JTable(data,name);
			table.setBounds(0, 0, 450, 450);
			pane=new JScrollPane(table);
			add(pane);
		}
参数如下

		private JTable table;
		private Object[][] data = {};
		private String[] name = {"number","name","sex","age","brith","collage"};
		JScrollPane pane = null;

从数据库里读出记录     用好rs.next()就可以了 , 需要注意rs.getObject()是从一开始的。

public void databaseInit(){
			try{
				rs = statement.executeQuery("select * from student");
				System.out.println("Success Init");
				int i=0;
				rs.last();
				data = new Object[rs.getRow()][6];
				System.out.println(rs.getRow());
				rs.beforeFirst();
				while (rs.next()){
					for(int j=0;j<6;j++){
						data[i][j]=rs.getObject(j+1);
						//System.out.print(rs.getObject(j+1)+" ");
					}
					System.out.println();
					i++;
				}
				installTable();
			}catch(Exception ex){
				System.out.println("Exception In databaseInit()");
			}
		}

判断年份是否合法
用DateFormat简单判断一下,格式有错的话抛出异常,不过MySQL的Date类型也会帮你检查数据是否正确,大月小月也会检查很强大

						Y=text4.getText();
						M=text5.getText();
						D=text6.getText();
						T=Y+"-"+M+"-"+D;
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						dateFormat.setLenient(true);
						try{
							dateFormat.parse(T);
						}catch(Exception ex){
							INData();
							System.out.println("Date");
						}

其他就没有什么了,纯体力活。完整代码如下。

import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;



public class MyDateBase {
	public static void main(String[] args) {
		try{
			Class.forName(driver);
			conn=DriverManager.getConnection(url,user,pass);
			if (!conn.isClosed()){
				System.out.println("Success");
				statement = conn.createStatement();
				rs = statement.executeQuery("select * from admin");
			}
		}catch(Exception e){
			System.out.println("exception");
		}
		MyLogin = new Login();
	}
	private static class MyCons extends GridBagConstraints {
		public MyCons(int a, int b, int c, int d) {
			super.weightx = 1;
			super.weighty = 1;
			super.gridx = a;
			super.gridy = b;
			super.gridwidth = c;
			super.gridheight = d;
		}
	}
	private static class Login extends JFrame implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			String userName;
			String passWd;
			if (e.getSource().equals(button1)) {
				userName=text1.getText();
				passWd=text2.getText();
				boolean b=false;
				try{
					while(rs.next()){
						System.out.println(rs.getString(1)+" "+rs.getString(2));
						//System.out.println(rs.getString(1)==userName+" "+rs.getString(2));
						if((rs.getString(1).equals(userName))&&(rs.getString(2).equals(passWd))){
							b=true;	
						}
					}
				}catch(Exception ex){
					
				}
				if(b)
					MyMain = new Main();
				this.dispose();
			}
			if (e.getSource().equals(button2)){
				this.dispose();
			}
		}

		public Login() {
			super("Login");
			setSize(200, 200);
			this.setVisible(true);
			init();
		}

		private void init() {
			button1.addActionListener(this);
			button2.addActionListener(this);
			setLayout(new GridBagLayout());
			add(label1, new MyCons(0, 0, 1, 1));
			add(text1, new MyCons(1, 0, 3, 1));
			add(label2, new MyCons(0, 1, 1, 1));
			add(text2, new MyCons(1, 1, 3, 1));
			add(button1, new MyCons(1, 2, 1, 1));
			add(button2, new MyCons(3, 2, 1, 1));
		}



		private JLabel label1 = new JLabel("UserID:");
		private JLabel label2 = new JLabel("PassWord:");
		private TextField text1 = new TextField(15);
		private TextField text2 = new TextField(15);
		private JButton button1 = new JButton("Login");
		private JButton button2 = new JButton("Exit");
	}

	private static class Main extends JFrame implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource().equals(Item_Insert)||e.getSource().equals(button1)) {
				MyInsert = new Insert();
			}
			else if (e.getSource().equals(Item_Exit)||e.getSource().equals(button2)){
				this.dispose();
			}
		}
		
		public Main() {
			super("Main");
			setSize(400, 400);
			setVisible(true);
			init();
		}

		private void init() {
			databaseInit();
			installMenu();
			installTollBar();
		}
		public void databaseInit(){
			try{
				rs = statement.executeQuery("select * from student");
				System.out.println("Success Init");
				int i=0;
				rs.last();
				data = new Object[rs.getRow()][6];
				System.out.println(rs.getRow());
				rs.beforeFirst();
				while (rs.next()){
					for(int j=0;j<6;j++){
						data[i][j]=rs.getObject(j+1);
						//System.out.print(rs.getObject(j+1)+" ");
					}
					System.out.println();
					i++;
				}
				installTable();
			}catch(Exception ex){
				System.out.println("Exception In databaseInit()");
			}
		}
		private void installTable(){
			table = new JTable(data,name);
			table.setBounds(0, 0, 450, 450);
			pane=new JScrollPane(table);
			add(pane);
		}
		private void installTollBar(){
			toolBar = new JToolBar();
			button1.addActionListener(this);
			button2.addActionListener(this);
			toolBar.add(button1);
			toolBar.add(button2);
			add(toolBar,BorderLayout.NORTH);
		}
		private void installMenu() {
			Mb = new JMenuBar();
			sysMenu = new JMenu("System");
			Item_Insert = new JMenuItem("Insert");
			Item_Exit = new JMenuItem("Exit");
			Item_Exit.addActionListener(this);
			Item_Insert.addActionListener(this);
			sysMenu.add(Item_Insert);
			sysMenu.add(Item_Exit);
			Mb.add(sysMenu);
			setJMenuBar(Mb);
		}

		private JMenuItem Item_Insert;
		private JMenuItem Item_Exit;
		private JMenuBar Mb;
		private JMenu sysMenu;
		private JPanel insertS;
		private JToolBar toolBar;
		private JButton button1 = new JButton("Ins");
		private JButton button2 = new JButton("Ext");
		private JTable table;
		private Object[][] data = {};
		private String[] name = {"number","name","sex","age","brith","collage"};
		JScrollPane pane = null;
	}

	private static class Insert extends JFrame implements ItemListener,ActionListener{
		@Override
		public void itemStateChanged(ItemEvent e) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void actionPerformed(ActionEvent e){
			String Y,M,D,T="";
			CheckDate=true;
			if (e.getSource().equals(button1)){
				String sql = "insert student values(";
				if (text1.getText().length()==10&&text2.getText().length()!=0){
					int age=Integer.parseInt(text3.getText());
					if(0<age&&age<100){
						Y=text4.getText();
						M=text5.getText();
						D=text6.getText();
						T=Y+"-"+M+"-"+D;
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
						dateFormat.setLenient(true);
						try{
							dateFormat.parse(T);
						}catch(Exception ex){
							INData();
							System.out.println("Date");
						}
						sql+="\""+text1.getText()+"\",";
						sql+="\""+text2.getText()+"\",";
						if (box1.isSelected())
							sql+="\""+"Male"+"\",";
						else 
							sql+="\""+"Female"+"\",";
						sql+=age+",";
						sql+="\""+T+"\",";
						sql+="\""+choice.getSelectedItem()+"\");";
						if (CheckDate)
							try{
								System.out.println(sql);
								statement.execute(sql);
								MyMain.dispose();
								MyMain=new Main();
								this.dispose();
							}catch(Exception ex){
								System.out.println("Exception in Insert");
							}
						
					}
				}
				else{
					INData();
				}
				
			}
			else if (e.getSource().equals(button2)){
				this.dispose();
			}
		}
		public Insert() {
			super("Insert");
			setSize(300, 300);
			setVisible(true);
			init();
		}
		private void INData(){
			System.out.println("Data Exception!");
			CheckDate=false;
			//this.dispose();
		}
		private void init(){
			setLayout(new GridBagLayout());
			add(label1,new MyCons(0,0,1,1));
			add(text1,new MyCons(1,0,3,1));
			//---------------------------------------
			add(label2,new MyCons(0,1,1,1));
			add(text2,new MyCons(1,1,3,1));
			//---------------------------------------
			add(label3,new MyCons(0,2,1,1));
			sexGroup.add(box1);
			sexGroup.add(box2);
			add(box1,new MyCons(1,2,1,1));
			add(box2,new MyCons(2,2,1,1));
			//---------------------------------------
			add(label4,new MyCons(0,3,1,1));
			add(text3,new MyCons(1,3,3,1));
			//---------------------------------------
			add(label5,new MyCons(0,4,1,1));
			add(text4,new MyCons(1,4,2,1));
			add(label7,new MyCons(3,4,1,1));
			add(text5,new MyCons(5,4,1,1));
			add(label8,new MyCons(6,4,1,1));
			add(text6,new MyCons(7,4,1,1));
			add(label9,new MyCons(8,4,1,1));
			//---------------------------------------
			choice.add("software1");
			choice.add("software2");
			choice.addItemListener(this);
			add(label6,new MyCons(0,5,1,1));
			add(choice,new MyCons(1,5,3,1));
			//---------------------------------------
			button1.addActionListener(this);
			button2.addActionListener(this);
			add(button1,new MyCons(0,6,1,1));
			add(button2,new MyCons(1,6,1,1));
			
		}
		private JLabel label1 = new JLabel("Number:");
		private JLabel label2 = new JLabel("Name:");
		private JLabel label3 = new JLabel("Sex:");
		private JLabel label4 = new JLabel("Age:");
		private JLabel label5 = new JLabel("Brith:");
		private JLabel label6 = new JLabel("College");
		private JLabel label7 = new JLabel("Y");
		private JLabel label8 = new JLabel("M");
		private JLabel label9 = new JLabel("D");
		private JTextField text1 = new JTextField(10);
		private JTextField text2 = new JTextField(10);
		private JTextField text3 = new JTextField(10);
		private JTextField text4 = new JTextField(5);
		private JTextField text5 = new JTextField(3);
		private JTextField text6 = new JTextField(3);
		private ButtonGroup sexGroup = new ButtonGroup();
		private JRadioButton box1 = new JRadioButton("male",true);
		private JRadioButton box2 = new JRadioButton("female",false);
		private Choice choice = new Choice();
		private JButton button1 = new JButton("Submit");
		private JButton button2 = new JButton("Exit");
		private  boolean CheckDate;
	}
	private class MyException extends Exception{
		
	}
	private static Login MyLogin;
	private static Main MyMain;
	private static Insert MyInsert;
	
	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://127.0.0.1:3306/hit";
	private static String user="root";
	private static String pass="nihaoa";
	private static Connection conn;
	private static ResultSet rs;
	private static Statement statement;
}


你可能感兴趣的:(java,数据库,exception,String,insert,button)