時間:2023-05-23 15:48:01 | 來源:網(wǎng)站運營
時間:2023-05-23 15:48:01 來源:網(wǎng)站運營
Java實戰(zhàn)Tomcat+Servlet+Sql開發(fā)簡單網(wǎng)站配置環(huán)境:/* * 這里放的是 靜態(tài)Sql代碼*/public class SqlCode { // 在數(shù)據(jù)students中創(chuàng)建表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位學(xué)生的所有信息 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"; //刪除某個學(xué)號 自己測試數(shù)據(jù)用的 static String deleteByIdSql = "USE students" + "/n" + "DELETE FROM scores WHERE sno = ";}
class sqlServer{ private Connection connection = null; //連接接口實例 private Statement statmment = null; //執(zhí)行靜態(tài)sql的接口實例 private PreparedStatement preStatement = null; //執(zhí)行動態(tài)sql的接口實例 private ResultSet resSet = null; // sql查詢的返回數(shù)據(jù)集合 String dbName = "students"; //數(shù)據(jù)庫名 String tbName = "scores"; //數(shù)據(jù)表名 沒必要其實 String url = "jdbc:sqlserver://127.0.0.1:1433"; //sqlserver連接地址url String userName = "sa"; //sqlserver的賬號名 要在SMSS安全性里面設(shè)置 String passWord = "root"; //sqlserver的賬號的密碼 要在SMSS安全性里面設(shè)置 //下面就是按課題要求寫的一些靜態(tài)代碼(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; //無參構(gòu)造函數(shù) 初始化建立連接 public sqlServer() { // TODO Auto-generated constructor stub try { //加載數(shù)據(jù)庫驅(qū)動 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //DriverManager接口獲取連接 this.connection = DriverManager.getConnection(url,userName,passWord); //獲取 執(zhí)行數(shù)據(jù)庫靜態(tài)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(); } } //有參構(gòu)造函數(shù) 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(); } } //關(guān)閉連接 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("關(guān)閉連接!"); connection.close(); } } //打印輸出 ResultSet集合中的數(shù)據(jù) 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(); } //查詢?nèi)?public ResultSet queryAll(String querySql) throws SQLException { return statmment.executeQuery(querySql); } //創(chuàng)建數(shù)據(jù)庫 public void generalExc(String sql) throws SQLException { preStatement = connection.prepareStatement(sql); preStatement.executeUpdate(); } //創(chuàng)建數(shù)據(jù)庫 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("創(chuàng)建數(shù)據(jù)庫"+dbName+"成功!"); } //刪除數(shù)據(jù)庫 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("刪除數(shù)據(jù)庫"+dbName+"成功!"); } //通過sno學(xué)號刪除 數(shù)據(jù)表中的記錄 public void delById(int sno) throws SQLException { preStatement = connection.prepareStatement(delByIdSql + sno); preStatement.executeUpdate(); System.out.println("刪除記錄"+"成功!"); } //創(chuàng)建數(shù)據(jù)表 public void createTable(String createSql) throws SQLException { statmment.execute(createSql); System.out.println("創(chuàng)建數(shù)據(jù)表"+"成功!"); } //插入數(shù)據(jù)到數(shù)據(jù)表 public void insertValue(String insertSql) throws SQLException { statmment.execute(insertSql); System.out.println("刪除數(shù)據(jù)表"+"成功!"); } //更新數(shù)據(jù)表中的數(shù)據(jù) public void updateValue(String updateSql) throws SQLException { statmment.execute(updateSql); System.out.println("更新完成!"); } //scanner輸入指定學(xué)號,查詢學(xué)生信息 public void inputSnoAndQuery() throws SQLException { Scanner inputScanner = new Scanner(System.in); int snoId = inputScanner.nextInt(); rsPrint(queryBySno(snoId)); } //返回值:把ResultSet集合中的數(shù)據(jù)轉(zhuǎn)換成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("查詢結(jié)果如下: "+"/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; //執(zhí)行自定義sql代碼的查詢按鈕 public JButton noResultBtn; //執(zhí)行沒有返回值的sql代碼的按鈕 比如:create insert delete 這些 public JButton createDBBtn; //創(chuàng)建數(shù)據(jù)庫按鈕 public JButton createTBBtn; //創(chuàng)建數(shù)據(jù)表按鈕 public JButton insertBtn; //添加數(shù)據(jù)按鈕 public JButton showBtn; //展示5個學(xué)生數(shù)據(jù)的按鈕 public JButton updateBtn; //更新數(shù)據(jù)的按鈕 男-5 女+3 public JButton querySnoBtn; //通過學(xué)號查詢的按鈕 public JLabel labelSouth; //底部標(biāo)簽 public JLabel labelNorth; //頂部標(biāo)簽 public sqlServer myServer; //把sqlServer作為內(nèi)部類 //窗口構(gòu)造函數(shù) 主要用來初始化組件 public window() { // TODO Auto-generated constructor stub this.sqlWindowFrame = new JFrame("by fishers _(′?`」 ∠)_"); //設(shè)置窗體 名字為notePad this.sqlWindowFrame.setLayout(new BorderLayout()); //邊界布局方式 this.sqlWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設(shè)置關(guān)閉框 this.sqlWindowFrame.setSize(800,500); this.textArea = new JTextArea(); this.scrollPane = new JScrollPane(textArea); this.inpuTextField = new JTextField(30); this.customQueryBtn = new JButton("執(zhí)行查詢"); this.noResultBtn = new JButton("執(zhí)行無返回值的sql"); this.createDBBtn = new JButton("創(chuàng)建數(shù)據(jù)庫"); this.createTBBtn = new JButton("創(chuàng)建數(shù)據(jù)表"); this.insertBtn = new JButton("添加數(shù)據(jù)"); this.showBtn = new JButton("展示數(shù)據(jù)"); this.updateBtn = new JButton("更新數(shù)據(jù)"); this.querySnoBtn = new JButton("查詢學(xué)號"); this.PanelSouth = new JPanel(); this.PanelNorth = new JPanel(); this.labelSouth = new JLabel("輸入sql語法: "); this.labelNorth = new JLabel("內(nèi)置功能區(qū): "); this.myServer = new sqlServer(); textArea.setFont(new Font("宋體",Font.PLAIN,20)); textArea.setEditable(false); //設(shè)置文本域組件不可以編輯 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); } //監(jiān)聽方法都寫在這里 public void addListen() { //監(jiān)聽自定義查詢按鈕 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(); } } } }); //監(jiān)聽沒有返回值的按鈕 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("執(zhí)行完成!"); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); //監(jiān)聽創(chuàng)建數(shù)據(jù)庫按鈕 createDBBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { myServer.createDataBase("students"); textArea.setText("創(chuàng)建數(shù)據(jù)庫完成!"); } catch (SQLException e1) { // TODO Auto-generated catch block textArea.setText("創(chuàng)建數(shù)據(jù)庫失敗,請檢查語法是否正確!或當(dāng)前連接已經(jīng)存在該數(shù)據(jù)庫!"); e1.printStackTrace(); } } }); //監(jiān)聽創(chuàng)建數(shù)據(jù)表的按鈕 createTBBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { myServer.createTable(myServer.createTableSql); textArea.setText("創(chuàng)建數(shù)據(jù)表完成!"); } catch (SQLException e1) { textArea.setText("創(chuàng)建數(shù)據(jù)表失敗,請檢查語法是否正確!或當(dāng)前數(shù)據(jù)庫中已經(jīng)存在該數(shù)據(jù)表!"); e1.printStackTrace(); } } }); //監(jiān)聽插入數(shù)據(jù)的按鈕 insertBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { myServer.insertValue(myServer.insertSql); textArea.setText("添加數(shù)據(jù)完成!"); } catch (SQLException e1) { textArea.setText("添加數(shù)據(jù)失敗,請檢查語法是否正確!或當(dāng)前數(shù)據(jù)庫中已經(jīng)存在該數(shù)據(jù)!"); e1.printStackTrace(); } } }); //監(jiān)聽展示數(shù)據(jù)的按鈕 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(); } } }); //監(jiān)聽更新數(shù)據(jù)的按鈕 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("更新數(shù)據(jù)完成!"); } catch (SQLException e1) { // TODO Auto-generated catch block textArea.setText("更新數(shù)據(jù)失敗,請檢查語法是否正確!"); e1.printStackTrace(); } } }); //監(jiān)聽通過學(xué)號查詢數(shù)據(jù)的按鈕 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 = "未查到該學(xué)生信息";// 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"); //創(chuàng)建數(shù)據(jù)庫// myServer.createTable(myServer.createTableSql); //創(chuàng)建數(shù)據(jù)表// 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(); //關(guān)閉連接// myServer.inputSnoAndQuery();// myServer.updateValue(myServer.updateBoySql);// myServer.delDataBase("students");// myServer.createDataBase("qwertest12"); window myWindow = new window(); //最后還是做成了窗口 orz }}
The Apache Tomcat installation at this directory is version 8.5.38. A Tomcat 8.0 installation is expected.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>歡迎頁面</title></head><body> 歡迎使用eclipse部署Tomcat。</body></html>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); Connection connection = null; //連接接口實例 Statement statmment = null; //執(zhí)行靜態(tài)sql的接口實例 PreparedStatement preStatement = null; //執(zhí)行動態(tài)sql的接口實例 ResultSet resultSet = null; //sql查詢的返回數(shù)據(jù)集合 String userName = "sa"; //數(shù)據(jù)庫賬號 String passWord = "root"; //數(shù)據(jù)庫密碼 String url = "jdbc:sqlserver://127.0.0.1:1433"; //sqlserver連接地址url int sno = 0; String name = null; String ssex = null; int score = 0; //加載數(shù)據(jù)庫驅(qū)動 try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //DriverManager接口獲取連接 try { connection = DriverManager.getConnection(url,userName,passWord); //獲取 執(zhí)行數(shù)據(jù)庫靜態(tài)SQL語法的接口 statmment = connection.createStatement(); if(connection != null) { System.out.println("連接成功!"); } //從數(shù)據(jù)庫中 獲取一位同學(xué)的個人信息 String querySqlString = "" + "USE students" + "/n" + "SELECT TOP 1* FROM scores"; resultSet = statmment.executeQuery(querySqlString); while(resultSet.next()) { sno = resultSet.getInt("sno"); name = resultSet.getString("name"); ssex = resultSet.getString("ssex"); score = resultSet.getInt("score"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //用setAttribute設(shè)置傳遞的數(shù)據(jù)參數(shù) request.setAttribute ( "sno", sno) ; request.setAttribute ( "name", name) ; request.setAttribute ( "ssex", ssex) ; request.setAttribute ( "score", score) ; //重要的是getRequestDispatcher 把數(shù)據(jù)交給jsp頁面響應(yīng) request.getRequestDispatcher ( "NewFile.jsp").forward( request , response );//轉(zhuǎn)發(fā)到NewFile.jsp,讓他去具體響應(yīng) }
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><!DOCTYPE html><html><head><meta charset="utf-8"><title>Insert title here</title></head><body>用戶學(xué)號:${sno} 用戶姓名:${name} 用戶性別:${ssex} 用戶分數(shù):${score}</body></html>
關(guān)鍵詞:簡單,配置,環(huán)境,實戰(zhàn)
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。