Java使用JDBC連接SQL Server數據庫|實現學生成績信息系統


Java實驗四 JDBC
使用SQL Server數據庫或者MySQL數據庫各自的客戶端工具,完成如下任務:
(1)創建數據庫students;
(2)在數據students中創建表scores,包括如下字段:學號、姓名、性別、得分,字段類型自行定義。學號為主鍵。
接着使用JDBC編寫Java程序,完成如下任務:
(1)在表格scores插入5條記錄,代表5個學生,三位男生二位女生,各字段內容自定(“得分”字段填入自定分數);
(2)顯示5位學生的所有信息;
(3)將三位男生的得分減去5分,將兩位女生的成績加上3分;
(4)從鍵盤輸入不同學號,根據學號顯示相應學生的所有信息。

做成了窗口,界面是這樣的

1.安裝JDBC,配置SqlServer

可以參考之前寫的博客:Java使用JDBC連接SQL Server數據庫
注意Java的版本,java7、8、12要安裝不同的包。
記得重啟電腦。

2.寫代碼

文件目錄是這樣的

兩個文件,

SqlCode.java

SqlCode.java存放靜態SQL代碼


/*
 * 這里放的是 靜態Sql代碼
*/

public class SqlCode {
	
	// 在數據students中創建表scores
	static String createTable = ""
			+ "USE students;"
			+ "\n"
			+ "CREATE TABLE scores"
			+ "("
			+ "sno int not null,"
			+ "name varchar(20) not null,"
			+ "ssex varchar(10) CHECK(ssex IN('boy','girl')),"
			+ "score int not null,"
			+ "PRIMARY KEY(sno),"
			+ ")";
	
	//在表格scores插入5條記錄
	static String insertValues = ""
			+ "USE students"
			+ "\n"
			+ "INSERT INTO scores(sno,name,ssex,score) VALUES(1,'DaWang','boy','61')"
			+ "\n"
			+ "INSERT INTO scores(sno,name,ssex,score) VALUES(2,'ErWang','girl','62')"
			+ "\n"
			+ "INSERT INTO scores(sno,name,ssex,score) VALUES(3,'SanWang','boy','63')"
			+ "\n"
			+ "INSERT INTO scores(sno,name,ssex,score) VALUES(4,'siWang','girl','65')"
			+ "\n"
			+ "INSERT INTO scores(sno,name,ssex,score) VALUES(5,'wuWang','girl','66')";

	//顯示5位學生的所有信息
	static String queryString = ""
			+ "USE students"
			+ "\n"
			+ "SELECT TOP 5 * FROM scores"; 
	
	//將三位男生的得分減去5 tucao:男生真累
	static String updateScoreBoy = ""
			+ "USE students"
			+ "\n"
			+ "UPDATE scores "
			+ "\n"
			+ "SET score = score - 5"
			+ "\n"
			+ "WHERE ssex = 'boy'"
			+ "\n";
	
	//將兩位女生的成績加上3分
	static String updateScoreGirl = ""
			+ "USE students"
			+ "\n"
			+ "UPDATE scores "
			+ "\n"
			+ "SET score = score + 3"
			+ "\n"
			+ "WHERE ssex = 'girl'"
			+ "\n";
	
	//刪除某個學號 自己測試數據用的
	static String deleteByIdSql = "USE students"
			+ "\n"
			+ "DELETE FROM scores WHERE sno = ";
}

SqlServerStu.java

SqlServerStu.java文件就是主文件,使用JDBC來操作數據庫了,最后還是做成了花里胡哨的窗口。。一共450行 (´ཀ`」 ∠)


class sqlServer{
	
	private Connection connection = null; //連接接口實例
	private Statement statmment = null; //執行靜態sql的接口實例
	private PreparedStatement preStatement = null; //執行動態sql的接口實例
	private ResultSet resSet = null; // sql查詢的返回數據集合
	
	String dbName = "students"; //數據庫名
	String tbName = "scores"; //數據表名 沒必要其實
	String url = "jdbc:sqlserver://127.0.0.1:1433"; //sqlserver連接地址url
	String userName = "sa";  //sqlserver的賬號名 要在SMSS安全性里面設置
	String passWord = "root"; //sqlserver的賬號的密碼 要在SMSS安全性里面設置
	
	//下面就是按課題要求寫的一些靜態代碼(String字符串類型,在SqlCode.java文件中的全局變量)
	String createTableSql = SqlCode.createTable;
	String insertSql = SqlCode.insertValues;
	String queryAllSql = SqlCode.queryString;
	String updateBoySql = SqlCode.updateScoreBoy;
	String updateGrilSql = SqlCode.updateScoreGirl;
	String delByIdSql = SqlCode.deleteByIdSql;

	//無參構造函數 初始化建立連接
	public sqlServer() {
		// TODO Auto-generated constructor stub
		try {
			//加載數據庫驅動
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//DriverManager接口獲取連接
			this.connection = DriverManager.getConnection(url,userName,passWord);
			//獲取 執行數據庫靜態SQL語法的接口
			this.statmment = connection.createStatement();
			if(connection != null) {
				System.out.println("連接成功!");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//有參構造函數 urlParam初始化建立連接
	public sqlServer(String urlParam) {
		// TODO Auto-generated constructor stub
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			this.connection = DriverManager.getConnection(urlParam);
			this.statmment = connection.createStatement();
			if(connection != null) {
				System.out.println("連接成功!");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//關閉連接
	public void close() throws SQLException {
		if(resSet != null) {
			resSet.close();
		}
		if(statmment != null) {
			statmment.close();
		}
		if(preStatement != null) {
			preStatement.close();
		}
		if(connection != null) {
			System.out.println("關閉連接!");
			connection.close();
		}
	}
	
	//打印輸出 ResultSet集合中的數據
	public void rsPrint(ResultSet rS) throws SQLException {
		if(rS == null) return;
		System.out.println("");
		System.out.println("sno"+"|   name"+"   | ssex"+"  | score");
		while(rS.next()) {
			int sno = rS.getInt("sno");
			String name = rS.getString("name");
			String ssex = rS.getString("ssex");
			int score = rS.getInt("score");
			System.out.println(sno+"  |  "+name+"  |  "+ssex+"  |  "+score);
		}
	}
	
	//返回ResultSet集合
	public ResultSet queryBySno(int snoId) throws SQLException {
		String queryByIdString = ""
				+ "USE students"
				+ "\n"
				+ "SELECT * FROM scores"
				+ "\n"
				+ "WHERE scores.sno = ?"
				+ "";
		this.preStatement = connection.prepareStatement(queryByIdString);
		preStatement.setInt(1, snoId);
		return preStatement.executeQuery();
	}

	//查詢全部
	public ResultSet queryAll(String querySql) throws SQLException {
		return statmment.executeQuery(querySql);
	}

	//創建數據庫
	public void generalExc(String sql) throws SQLException {
		preStatement = connection.prepareStatement(sql);
		preStatement.executeUpdate();
	}
	
	//創建數據庫
	public void createDataBase(String dbName) throws SQLException {
		String createSql = "CREATE DATABASE "+dbName;
		preStatement = connection.prepareStatement(createSql);
//		preStatement.setString(1, dbName);
		preStatement.executeUpdate();
		System.out.println("創建數據庫"+dbName+"成功!");
	}
	
	//刪除數據庫
	public void delDataBase(String dbName) throws SQLException {
		String deleteSql = "DROP DATABASE "+dbName;
		preStatement = connection.prepareStatement(deleteSql);
//		preStatement.setString(1, dbName);
		preStatement.executeUpdate();
		System.out.println("刪除數據庫"+dbName+"成功!");
	}
	
	//通過sno學號刪除 數據表中的記錄
	public void delById(int sno) throws SQLException {
		preStatement = connection.prepareStatement(delByIdSql + sno);
		preStatement.executeUpdate();
		System.out.println("刪除記錄"+"成功!");
	}
	
	//創建數據表
	public void createTable(String createSql) throws SQLException {
		statmment.execute(createSql);
		System.out.println("創建數據表"+"成功!");
	}
	
	//插入數據到數據表
	public void insertValue(String insertSql) throws SQLException {
		statmment.execute(insertSql);
		System.out.println("刪除數據表"+"成功!");
	}
	
	//更新數據表中的數據
	public void updateValue(String updateSql) throws SQLException {
		statmment.execute(updateSql);
		System.out.println("更新完成!");
	}
	
	//scanner輸入指定學號,查詢學生信息
	public void inputSnoAndQuery() throws SQLException {
		Scanner inputScanner = new Scanner(System.in);
		int snoId = inputScanner.nextInt();
		rsPrint(queryBySno(snoId));
	}

	//返回值:把ResultSet集合中的數據轉換成String類型  (因為后面展示到窗口文本域需要string類型)
	public String returnString(ResultSet rS) throws SQLException {
		// TODO Auto-generated method stub
		StringBuffer myBuffer = new StringBuffer();
		int line = 0;
		while(rS.next()) {
			if(line == 0) {
				line++;
				myBuffer.append("查詢結果如下: "+"\n");
//				myBuffer.append("sno"+"|   name"+"   | ssex"+"  | score"+"\n");
			}
			int sno = rS.getInt("sno");
			String name = rS.getString("name");
			String ssex = rS.getString("ssex");
			int score = rS.getInt("score");
			myBuffer.append(sno+"  |  "+name+"  |  "+ssex+"  |  "+score+"\n");
		}
		if(line == 0) myBuffer.append("");
		return myBuffer.toString();
	}
	
}

class window{
	//組件
	public JFrame sqlWindowFrame;
	public JPanel PanelSouth;
	public JPanel PanelNorth;
	public JTextArea textArea;
	public JScrollPane scrollPane;
	public JTextField inpuTextField;
	
	//一系列按鈕
	public JButton customQueryBtn; //執行自定義sql代碼的查詢按鈕
	public JButton noResultBtn; //執行沒有返回值的sql代碼的按鈕 比如:create insert delete 這些
	public JButton createDBBtn; //創建數據庫按鈕
	public JButton createTBBtn; //創建數據表按鈕
	public JButton insertBtn; //添加數據按鈕
	public JButton showBtn; //展示5個學生數據的按鈕
	public JButton updateBtn; //更新數據的按鈕 男-5 女+3
	public JButton querySnoBtn; //通過學號查詢的按鈕
	public JLabel labelSouth; //底部標簽 
	public JLabel labelNorth; //頂部標簽
	
	public sqlServer myServer; //把sqlServer作為內部類
	
	//窗口構造函數  主要用來初始化組件
	public window() {
		// TODO Auto-generated constructor stub
		this.sqlWindowFrame = new JFrame("by fishers _(´ཀ`」 ∠)_"); //設置窗體 名字為notePad
		this.sqlWindowFrame.setLayout(new BorderLayout()); //邊界布局方式
		this.sqlWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設置關閉框
		this.sqlWindowFrame.setSize(800,500);
		
		this.textArea = new JTextArea();
		this.scrollPane = new JScrollPane(textArea);
		
		this.inpuTextField = new JTextField(30);
		this.customQueryBtn = new JButton("執行查詢");
		this.noResultBtn = new JButton("執行無返回值的sql");
		this.createDBBtn = new JButton("創建數據庫");
		this.createTBBtn = new JButton("創建數據表");
		this.insertBtn = new JButton("添加數據");
		this.showBtn = new JButton("展示數據");
		this.updateBtn = new JButton("更新數據");
		this.querySnoBtn = new JButton("查詢學號");
		this.PanelSouth = new JPanel();
		this.PanelNorth = new JPanel();
		this.labelSouth = new JLabel("輸入sql語法: ");
		this.labelNorth = new JLabel("內置功能區: ");
		this.myServer = new sqlServer();
		textArea.setFont(new Font("宋體",Font.PLAIN,20));
		textArea.setEditable(false); //設置文本域組件不可以編輯
		itemAdd();
		addListen();
	}
	
	//添加組件都寫在這里
	public void itemAdd() {
		
		PanelSouth.add(labelSouth);
		PanelSouth.add(inpuTextField);
		PanelSouth.add(customQueryBtn);
		PanelSouth.add(noResultBtn);
		PanelSouth.add(noResultBtn);
		PanelNorth.add(labelNorth);
		PanelNorth.add(createDBBtn);
		PanelNorth.add(createTBBtn);
		PanelNorth.add(insertBtn);
		PanelNorth.add(showBtn);
		PanelNorth.add(updateBtn);
		PanelNorth.add(querySnoBtn);	
		
		sqlWindowFrame.add(scrollPane,BorderLayout.CENTER);
		sqlWindowFrame.add(PanelSouth,BorderLayout.SOUTH);
		sqlWindowFrame.add(PanelNorth,BorderLayout.NORTH);
		sqlWindowFrame.setVisible(true);
	}
	
	//監聽方法都寫在這里
	public void addListen() {
		//監聽自定義查詢按鈕
		customQueryBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String textString = inpuTextField.getText();
				System.out.println(textString);
				if(textString != null) {
					try {
//						myServer.rsPrint(myServer.queryAll(textString));
						String queryAns = myServer.returnString(myServer.queryAll(textString));
						System.out.println(queryAns);
						textArea.setText(queryAns);
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});

		//監聽沒有返回值的按鈕
		noResultBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				String textString = inpuTextField.getText();
				System.out.println(textString);
				if(textString != null) {
					try {
						myServer.generalExc(textString);
						textArea.setText("執行完成!");
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
		});

		//監聽創建數據庫按鈕
		createDBBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					myServer.createDataBase("students");
					textArea.setText("創建數據庫完成!");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					textArea.setText("創建數據庫失敗,請檢查語法是否正確!或當前連接已經存在該數據庫!");
					e1.printStackTrace();
				}
			}
		});
		
		//監聽創建數據表的按鈕
		createTBBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					myServer.createTable(myServer.createTableSql);
					textArea.setText("創建數據表完成!");
				} catch (SQLException e1) {
					textArea.setText("創建數據表失敗,請檢查語法是否正確!或當前數據庫中已經存在該數據表!");
					e1.printStackTrace();
				}
			}
		});
		
		//監聽插入數據的按鈕
		insertBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					myServer.insertValue(myServer.insertSql);
					textArea.setText("添加數據完成!");
				} catch (SQLException e1) {
					textArea.setText("添加數據失敗,請檢查語法是否正確!或當前數據庫中已經存在該數據!");
					e1.printStackTrace();
				}
			}
		});
		
		//監聽展示數據的按鈕
		showBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					String queryAns = myServer.returnString(myServer.queryAll(myServer.queryAllSql));
					System.out.println(queryAns);
					textArea.setText(queryAns);
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		});
		
		//監聽更新數據的按鈕
		updateBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					myServer.updateValue(myServer.updateBoySql);
					myServer.updateValue(myServer.updateGrilSql);
					textArea.setText("更新數據完成!");
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					textArea.setText("更新數據失敗,請檢查語法是否正確!");
					e1.printStackTrace();
				}
			}
		});
		
		//監聽通過學號查詢數據的按鈕
		querySnoBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				try {
					int sno = Integer.valueOf(inpuTextField.getText());
					String queryAns = myServer.returnString(myServer.queryBySno(sno));
//					if(queryAns == " " || queryAns == null) queryAns = "未查到該學生信息";
//					System.out.println(queryAns);
					textArea.setText(queryAns);
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					textArea.setText("查詢失敗,請檢查語法是否正確");
					e1.printStackTrace();
				}
			}
		});
	}
}

//主進程啟動
public class SqlServerStu {
	public static void main(String []args) throws SQLException {
//		String urlParam = "jdbc:sqlserver://127.0.0.1:1433?user=sa&password=root"; //這個連接url好像不能用啊
//		sqlServer myServer = new sqlServer();
//		myServer.createDataBase("students"); //創建數據庫
//		myServer.createTable(myServer.createTableSql); //創建數據表
//		myServer.insertValue(myServer.insertSql); //增
//		myServer.rsPrint(myServer.queryAll(myServer.queryAllSql)); //查
//		myServer.rsPrint(myServer.queryBySno(2)); //查
//		myServer.updateValue(myServer.updateBoySql); //改
//		myServer.delById(1); //刪
//		myServer.rsPrint(myServer.queryAll(myServer.queryAllSql)); //查
//		myServer.delDataBase("students"); //刪
//		myServer.close(); //關閉連接
//		myServer.inputSnoAndQuery();
//		myServer.updateValue(myServer.updateBoySql);
//		myServer.delDataBase("students");
//		myServer.createDataBase("qwertest12");
		window myWindow = new window(); //最后還是做成了窗口 orz
	}
}
//湊夠450行

做數據庫實驗也是可以的??


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM