- 2019-03-31
import java.sql.SQLException;//捕獲問題
import java.sql.Connection;//連接數據庫
import java.sql.DriverManager;//DriverManager管理一組 JDBC 驅動程序的基本服務。DataSource 接口是 JDBC 2.0 API 中的新增內容,它提供了連接到數據源的另一種方法。使用 DataSource 對象是連接到數據源的首選方法。
import java.sql.PreparedStatement;//使用preparedStatement進行增刪改查
public class JDBCUtil { public static Connection getConn() //定義靜態方法 靜態方法可以直接用調用 JDBCutil.getConn()
//如Connection a = JDBCUtil.getconn();
//而非靜態方法 public aa()
// 只能用 aa b = new aa();
{ Connection connection=null; try { Class.forName("com.mysql.jdbc.Driver"); //返回一個類 String url ="jdbc:mysql://localhost:3306/grades?user=root&password=123"; connection =DriverManager.getConnection(url); } catch (ClassNotFoundException e) { System.out.println("JDBC connection error"); } catch (SQLException e) { //SQLException 用來捕獲問題 System.out.println("JDBC operation error"); } return connection; } public static void closeConn(PreparedStatement preStmt,Connection conn) { if(preStmt!=null) { try { preStmt.close();//關閉鏈接 } catch(SQLException e) { System.out.println("PreparedStatement close error"); } } if(conn!=null) { try { conn.close();//關閉連接避免占用過多資源 }catch(SQLException e) { System.out.println("PreparedStatement close error"); } } } }
package cn.edu.hbue.xyl.gui; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.Scanner; public class InsertExample { public static void main(String[] args) { Connection connection =JDBCUtil.getConn(); PreparedStatement preStmt =null; try { String sql ="insert into stock(orderId,sName,consignmentDate,baleName,count,money)values(?,?,?,?,?,?)"; preStmt =connection.prepareStatement(sql); preStmt.setInt(1, 1235); preStmt.setString(2, "餅干"); preStmt.setString(3, "2013-6-29"); preStmt.setString(4, "小陳"); preStmt.setInt(5, 20); preStmt.setDouble(6, 223); preStmt.executeUpdate();//返回更新的數據行數 System.out.println("添加數據的行數為"+preStmt.getUpdateCount()); } catch (SQLException e) { System.out.println("JDBC operation error"); }finally { JDBCUtil.closeConn(preStmt, connection); } } }
其中execute 和 exeupDate 和 executeQuery區別參考 大佬:
https://www.cnblogs.com/angelye/p/7855906.html
import java.awt.Container; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class InsertStockFrame extends JFrame implements ActionListener{ private JTextField orderIdTextField; //JTextField表示的是文本框 詳情https://zhidao.baidu.com/question/288180446.html private JTextField sNameTextField; private JTextField consignmentDateTextField; private JTextField baleNameTextField; private JTextField countTextField; private JTextField moneyTextField; private JLabel orderLabel;//JLabel 對象可以顯示文本、圖像或同時顯示二者。 詳情http://outofmemory.cn/code-snippet/1121/swing-JLabel-explain-in-detail-yiji-usage-shili private JLabel sNameLabel; private JLabel dateLabel; private JLabel baleNameLabel; private JLabel countLabel; private JLabel moneyLabel; private JLabel starLabel; private JButton confirmButton; private JButton cancelButton; public InsertStockFrame(){ setTitle("進貨"); setSize(220, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用戶單擊窗口的關閉按鈕時程序執行的操作 Container cp = this.getContentPane();//this.getContentPane()的作用是初始化一個容器,用來在容器上添加一些控件 cp.setLayout(new FlowLayout());//setLayout是對當前組件設置為流式布局.組件在窗體中從左到右依次排列 orderLabel = new JLabel("訂單號"); cp.add(orderLabel); orderIdTextField = new JTextField(10); cp.add(orderIdTextField); starLabel = new JLabel("*"); cp.add(starLabel); baleNameLabel = new JLabel("商品名稱"); cp.add(baleNameLabel); baleNameTextField = new JTextField(10); cp.add(baleNameTextField); starLabel = new JLabel("*"); cp.add(starLabel); dateLabel = new JLabel("交貨日期"); cp.add(dateLabel); consignmentDateTextField= new JTextField(10); cp.add(consignmentDateTextField); starLabel = new JLabel("*"); cp.add(starLabel); sNameLabel = new JLabel("客 戶"); cp.add(sNameLabel); sNameTextField = new JTextField(10); cp.add(sNameTextField); starLabel = new JLabel("*"); cp.add(starLabel); countLabel = new JLabel("數 量"); cp.add(countLabel); countTextField = new JTextField(10); cp.add(countTextField); starLabel = new JLabel("*"); cp.add(starLabel); moneyLabel = new JLabel("金 額"); cp.add(moneyLabel); moneyTextField = new JTextField(10); cp.add(moneyTextField); starLabel = new JLabel("*"); cp.add(starLabel); confirmButton = new JButton("添加"); confirmButton.addActionListener(this);// 建立事件監聽事件 https://blog.csdn.net/qq_41978199/article/details/80642012 cp.add(confirmButton); cancelButton = new JButton("取消"); cancelButton.addActionListener(this); cp.add(cancelButton); } public void actionPerformed(ActionEvent e) { //actionPerformed 用於接收操作事件的偵聽器接口 if(e.getActionCommand().equals("添加")){ //從各控件取出數據 String orderId = orderIdTextField.getText(); String sName = sNameTextField.getText(); String date = consignmentDateTextField.getText(); String baleName = baleNameTextField.getText(); String count = countTextField.getText(); String money = moneyTextField.getText(); //此處補充代碼 //非空或必填字段檢測 if(orderId.equals("")){ //如果內容為空 JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } if(sName.equals("")){ JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } if(date.equals("")){ JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } if(baleName.equals("")){ JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } if(count.equals("")){ JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } if(money.equals("")){ JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } //此處補充代碼 //進貨日期,數量,金額的合法性檢驗 int c = 0; double m ; int flag = 0; //非常關鍵!! 不然程序會重復輸出 try { c = Integer.parseInt(count);//Integer.parseInt(String)的作用就是將String字符類型數據轉換為Integer整型數據 m = Double.parseDouble(money); } catch(NumberFormatException t) { JOptionPane.showMessageDialog(getContentPane(), "請將帶星號的內容填寫完整!","信息提示框", JOptionPane.INFORMATION_MESSAGE); return ; } JDBCUtil genConnection = new JDBCUtil() ; Connection conn = genConnection.getConn(); String sql = "insert into stock(orderId,sName,consignmentDate,baleName,count,money)"+ " values(?,?,?,?,?,?)"; PreparedStatement preStmt = null; try { preStmt= conn.prepareStatement(sql); preStmt.setString(1, orderId); preStmt.setString(2, sName); preStmt.setString(3, date); preStmt.setString(4, baleName); preStmt.setInt(5, c); preStmt.setDouble(6, m); preStmt.executeUpdate(); System.out.println("成功插入數據"+ preStmt.getUpdateCount() + "條"); } catch (SQLException t) { flag = 1; t.printStackTrace(); }finally { JDBCUtil.closeConn(preStmt, conn); } try { if (flag == 0) { JOptionPane.showMessageDialog(getContentPane(), "插入成功","信息提示框", JOptionPane.INFORMATION_MESSAGE); orderIdTextField.setText(""); //成功或失敗以后將文本框清零 sNameTextField.setText(""); consignmentDateTextField.setText(""); baleNameTextField.setText(""); countTextField.setText(""); moneyTextField.setText(""); } else { JOptionPane.showMessageDialog(getContentPane(), "插入失敗","信息提示框", JOptionPane.INFORMATION_MESSAGE); orderIdTextField.setText(""); sNameTextField.setText(""); consignmentDateTextField.setText(""); baleNameTextField.setText(""); countTextField.setText(""); moneyTextField.setText(""); } } catch(HeadlessException t) { t.printStackTrace(); } } else { System.exit(0); //直接退出程序 } } public static void main(String[] args){ InsertStockFrame insert = new InsertStockFrame(); //調用前面方法 insert.setVisible(true); } }
實現如下
package cn.edu.hbue.xyl.gui; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class get { public static void main(String[] args) { Connection conn = JDBCUtil.getConn(); String sql = "select * from stock where consignmentDate= '2018-03-22' ";//where id = 1; 如果是日期得加上單引號'' PreparedStatement preStmt = null; ResultSet rs = null; try { preStmt = conn.prepareStatement(sql); rs = preStmt.executeQuery(); //執行后返回代表查詢結果的ResultSet對象。 while(rs.next()) { System.out.println("訂單號=" + rs.getInt(2)); System.out.println("貨品名稱:" + rs.getString(3)); System.out.println("交貨日期:" + rs.getDate(4)); System.out.println("數量:" + rs.getInt("count")); System.out.println("金額=" + rs.getDouble("money")); } }catch(SQLException e) { e.printStackTrace(); } } }
-
package cn.edu.hbue.xyl.gui; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; public class AllDataValues extends AbstractTableModel { //JTable用法 https://blog.csdn.net/edc3001/article/details/83386713 Object[][] values ; String[] headerNames = {"訂單號", "客戶" ,"交貨日期", "貨物名稱", "數量","金額"}; public AllDataValues(){ getValues(); } private void getValues(){ Connection conn = JDBCUtil.getConn(); PreparedStatement stmt= null; ResultSet rs = null; PreparedStatement preStmt = null; //使用 preparedStatement對象 preStmt來進行增刪改查 ArrayList list ;//多維數組 String sql = "select * from stock "; String countSql = "select count(id) from stock"; try { stmt = conn.prepareStatement(countSql); rs = stmt.executeQuery();//執行查詢;要用statement類的executeQuery()方法來下達select指令以查詢數據庫,executeQuery()方法會把數據庫響應的查詢結果存放在ResultSet類對象中供我們使用。即語句:ResultSet rs=s.executeQuery(sql); int rows = 0; while(rs.next()) rows = rs.getInt(1); values = new Object[rows][]; stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); int i =0; while(rs.next()){ list = new ArrayList();// 動態數組 有點類似於set<string> https://www.cnblogs.com/rickie/articles/67978.html String orderId = rs.getString("orderId"); list.add(orderId); String sName = rs.getString("sName"); list.add(sName); java.sql.Date consignmentDate = rs.getDate("consignmentDate"); list.add(consignmentDate); String baleName = rs.getString("baleName"); list.add(baleName); Integer count = rs.getInt("count"); list.add(count); Double money = rs.getDouble("money"); list.add(money); values[i] = new Object[list.size()]; values[i] = list.toArray(); i++; } } catch (SQLException e) { e.printStackTrace(); }finally{ JDBCUtil.closeConn(preStmt, conn); } } public int getColumnCount() { return values[0].length; } public int getRowCount() { return values.length; } public Object getValueAt(int row, int col) { return values[row][col]; } public String getColumnName(int col){ return headerNames[col]; } }
package cn.edu.hbue.xyl.gui; //調用前面方法
import java.awt.Container;
import java.awt.FlowLayout;import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;public class ShowDataFrame extends JFrame {
protected JTable table;
public ShowDataFrame(){
setSize(500,200);
setTitle("貨物一覽表");
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
AllDataValues dv = new AllDataValues();
table = new JTable(dv);
pane.add(new JScrollPane(table));
this.pack();
}
public static void main(String[] args){
ShowDataFrame s = new ShowDataFrame();
s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
s.setSize(500,200);
s.setVisible(true);
}
}
- 一般情況下程序直接寫在 main方法底下
- 當有extends或者implements其他接口的時候 用public 寫 比如: public Insert()然后在底下的main方法中調用 insert如: insert a = new insert();
- 寫其他的方法時候如 actionperformed 時候 用public void
- JFrame是調用窗口指令 記得最后要加上關閉窗口和setvisib(true) 不然窗口不可見或者無法關閉