IntelliJ IDEA+JFormDesigner+MSSQLSERVER 實戰2、JDBC封裝和數據訪問。

IntelliJ IDEA+JFormDesigner+MSSQLSERVER 實戰2、JDBC封裝和數據訪問。

首先在IntelliJ IDEA生成新的項目form,在項目的src下點添加new->java class  JDBC封裝和數據訪問 的新類JdbcUtils.java

類JdbcUtils 代碼如下:

package jdbcutils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//import java.sql.ResultSetMetaData;
import java.sql.SQLException;
//import java.util.ArrayList;
//import java.util.HashMap;
import java.util.List;
//import java.util.Map;
// import java.utiljdbcutils .Map;
import java.util.Properties;

public class JdbcUtils
{
    // 表示定義數據庫的用戶名
    private final String USERNAME = "sa";
    // 定義數據庫的密碼
    private final String PASSWORD = "3201319";
    // 定義數據庫的驅動信息
    private final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    // 定義訪問數據庫的地址
    private final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=bhjs";
    // 定義數據庫的鏈接
    private Connection connection;
    // 定義sql語句的執行對象
    private PreparedStatement pstmt;
    // 定義查詢返回的結果集合
    private ResultSet resultSet;

    public void JdbcUtils()
    {
        try
        {
            Class.forName(DRIVER);
            // System.out.println("註冊驅動成功!!");
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
    }

    // 定義獲得數據庫的鏈接
    public Connection getConnection()
    {
        try
        {
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            // System.out.println("數據庫連接成功");
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
        return connection;
    }

    public ResultSet  findMoreResult(String sql, List params) throws SQLException  //查詢返回多行值
    {
        int index = 1;
        ResultSet resultSet;
        pstmt = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty())
        {
            for (int i = 0; i < params.size(); i++)
            {
                pstmt.setObject(index++, params.get(i));
            }
        }
        resultSet = pstmt.executeQuery();

        return resultSet;
    }

    public boolean updateByPreparedStatement(String sql, List params) throws SQLException  //更新

    {
        boolean flag = false;
        int result = -1;// 表示當用戶執行添加刪除和修改的時候所影響數據庫的行數
        pstmt = connection.prepareStatement(sql);
        int index = 1;
        // 填充sql語句中的佔位符
        if (params != null && !params.isEmpty())
        {
            for (int i = 0; i < params.size(); i++)
            {
                pstmt.setObject(index++, params.get(i));
            }
        }
        result = pstmt.executeUpdate();
        flag = result > 0 ? true : false;
        return flag;
    }

    public void releaseConn()  //釋放連接
    {
        if (resultSet != null)
        {
            try
            {
                resultSet.close();
            }
            catch (SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (pstmt != null)
        {
            try
            {
                pstmt.close();
            }
            catch (SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null)
        {
            try
            {
                connection.close();
            }
            catch (SQLException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

2、建立新的 JFormDesigner 的窗口 form1

點tab form1.jfd添加新的窗口控件 5個按鈕JButton和一個JTable 控件

改寫 form1.java 代碼如下:

package com.company;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
//import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import jdbcutils.JdbcUtils;

/**
 * @author a
 */
public class form1 extends JFrame {
    public form1() {
        initComponents();
    }

    private void button1MouseClicked(MouseEvent e) {
        // TODO add your code here
        ///////////////////////////////////////////
        Connection con1 = null;
        PreparedStatement statement = null;
        ResultSet res = null;
        List parm1=null;
        try {

            JdbcUtils JdbcUtils2 =new JdbcUtils();
            JdbcUtils2.JdbcUtils();
            con1=JdbcUtils2.getConnection();

            String sql = "select * from info_jqmc ";//查詢test表
            res=JdbcUtils2.findMoreResult(sql,parm1);  //調用jdbc封裝類中  查詢函數

            Vector line1;
            Vector rows,columnNames;
            rows = new Vector();

            columnNames = new Vector();
            columnNames.add("jqmc");
            columnNames.add("jqip");


            while(res.next()){

                line1 = new Vector();
                line1.add(res.getString("jqmc"));
                line1.add(res.getString("jqip"));
               // label1.setText(res.getString("jqmc"));
                rows.add(line1);
            }
            //定義JTable的對象

             DefaultTableModel  model = new DefaultTableModel(rows, columnNames);
             table1.setModel( model);

            //table1.updateUI() ;
            // scrollPane1.validate();


            //  table1.invalidate();
            //table.addMouseListener(new MouseAdapter() {
            //   @Override
            //    public void mouseClicked(MouseEvent e) {
            //         int selectRows=table.getSelectedRows().length;// 取得用戶所選行的行數

            //        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();


            //        int selectedRowIndex = table.getSelectedRow(); // 取得用戶所選單行
            //         textField.setText((String)table.getValueAt(selectedRowIndex,0));
            //         textField_1.setText((String)table.getValueAt(selectedRowIndex,1));
            // 進行相關處理


            //  }
            // });

            //jScrollPane = new JScrollPane(table);
            //  jScrollPane.setToolTipText("");


            // jScrollPane.setBounds(43, 23, 534, 308);
            //  frmJdbc.getContentPane().add(jScrollPane);

        } catch (Exception e1) {
            // TODO: handle exception

            e1.printStackTrace();

        }finally{
            try {
                if(res != null) res.close();
                if(statement != null) statement.close();
                if(con1 != null) con1.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        /////////////////////////////////////////



    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        button1 = new JButton();
        button2 = new JButton();
        button3 = new JButton();
        button4 = new JButton();
        button5 = new JButton();
        scrollPane1 = new JScrollPane();
        table1 = new JTable();

        //======== this ========
        setTitle("\u6570\u636e\u8bbf\u95ee");
        Container contentPane = getContentPane();

        //---- button1 ----
        button1.setText("\u67e5\u8be2");
        button1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                button1MouseClicked(e);
            }
        });

        //---- button2 ----
        button2.setText("\u65b0\u589e");

        //---- button3 ----
        button3.setText("\u5220\u9664");

        //---- button4 ----
        button4.setText("\u4fdd\u5b58");

        //---- button5 ----
        button5.setText("\u9000\u51fa");

        //======== scrollPane1 ========
        {
            scrollPane1.setViewportView(table1);
        }

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addGroup(contentPaneLayout.createParallelGroup()
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addGap(77, 77, 77)
                            .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 501, GroupLayout.PREFERRED_SIZE))
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addGap(57, 57, 57)
                            .addComponent(button1)
                            .addGap(32, 32, 32)
                            .addComponent(button2)
                            .addGap(27, 27, 27)
                            .addComponent(button3)
                            .addGap(31, 31, 31)
                            .addComponent(button4)
                            .addGap(31, 31, 31)
                            .addComponent(button5)))
                    .addGap(56, 56, 56))
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addGap(37, 37, 37)
                    .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 351, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
                    .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(button1)
                        .addComponent(button2)
                        .addComponent(button3)
                        .addComponent(button4)
                        .addComponent(button5))
                    .addGap(21, 21, 21))
        );
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents

        ///////////////////////////////////////////
        Connection con = null;
        PreparedStatement statement = null;
        ResultSet res = null;
        List parm1=null;
        try {

            JdbcUtils JdbcUtils1 =new JdbcUtils();
            JdbcUtils1.JdbcUtils();
            con=JdbcUtils1.getConnection();

            String sql = "select * from info_jqmc ";//查詢test表
            res=JdbcUtils1.findMoreResult(sql,parm1);  //調用jdbc封裝類中  查詢函數

            Vector line1;
            Vector rows,columnNames;
            rows = new Vector();

            columnNames = new Vector();
            columnNames.add("jqmc");
            columnNames.add("jqip");


            while(res.next()){

                line1 = new Vector();
                line1.add(res.getString("jqmc"));
                line1.add(res.getString("jqip"));

                rows.add(line1);
            }
            //定義JTable的對象

            DefaultTableModel  model = new DefaultTableModel(rows, columnNames);
            table1.setModel( model);

            //table1.updateUI() ;
            // scrollPane1.validate();


            //  table1.invalidate();
            //table.addMouseListener(new MouseAdapter() {
            //   @Override
            //    public void mouseClicked(MouseEvent e) {
            //         int selectRows=table.getSelectedRows().length;// 取得用戶所選行的行數

            //        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();


            //        int selectedRowIndex = table.getSelectedRow(); // 取得用戶所選單行
            //         textField.setText((String)table.getValueAt(selectedRowIndex,0));
            //         textField_1.setText((String)table.getValueAt(selectedRowIndex,1));
            // 進行相關處理


            //  }
            // });

            //jScrollPane = new JScrollPane(table);
            //  jScrollPane.setToolTipText("");


            // jScrollPane.setBounds(43, 23, 534, 308);
            //  frmJdbc.getContentPane().add(jScrollPane);

        } catch (Exception e1) {
            // TODO: handle exception

            e1.printStackTrace();

        }finally{
            try {
                if(res != null) res.close();
                if(statement != null) statement.close();
                if(con != null) con.close();
            } catch (Exception e2) {
                // TODO: handle exception
                e2.printStackTrace();
            }
        }
        /////////////////////////////////////////

    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;
    private JScrollPane scrollPane1;
    private JTable table1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables


}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

改寫 Main.java(程序入口) 的代碼如下:

package com.company;
import javax.swing.JFrame;

public class Main {
    private JFrame frame;
    public static void main(String[] args) {
        // write your code here

        try {
            form1 form11 = new form1();   //定義我們用JFormDesigner 生成的窗口 form1的實例
            form11.setVisible(true);

            // form1.setBounds(400, 200, 636, 561);
            //form1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //form1.getContentPane().setLayout(null);
            //form1.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
////////////////////////////////////////////////////////////////////////

到此基本實現了 JFormDesigner 的窗口 的定義和JDBC封裝和數據訪問,點run編譯可出現如下窗口

完整代碼 稍後上傳.....

下載:鏈接: https://pan.baidu.com/s/1UqFMfB5gsKrlmDHZ6oUk0w 提取碼: 2ct3 

MS SQLSERVER 例子數據庫恢復數據庫文件 下載:

鏈接: https://pan.baidu.com/s/1ODmQhipjNhqLx_q0RtLkfA 提取碼: e4pg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章