IntelliJ IDEA + JFormDesigner + MSSQLSERVER実際の戦闘2.ウィンドウフォームアプリケーションとJDBCパッケージングおよびデータアクセスを確立します。

IntelliJ IDEA + JFormDesigner + MSSQLSERVER実際の戦闘2.ウィンドウフォームアプリケーションとJDBCパッケージングおよびデータアクセスを確立します。

まず、IntelliJ IDEAで新しいプロジェクトフォームを生成し、プロジェクトのsrcの下にnew-> javaクラスの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を作成します

タブ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パッケージングおよびデータアクセスは基本的に実現されています。[実行]をクリックしてコンパイルすると、次のウィンドウが表示されます

完全なコードがアップロードされました...

ダウンロード:リンク:https ://pan.baidu.com/s/1UqFMfB5gsKrlmDHZ6oUk0w抽出コード:2ct3 

MS SQLSERVERサンプルデータベースリカバリデータベースファイルのダウンロード:

リンク:https ://pan.baidu.com/s/1ODmQhipjNhqLx_q0RtLkfA抽出コード:e4pg

 

MSSQLSERVERに接続できない場合

1. SQLSERVERのsaのパスワードを設定し、SQLSERVERがsaとしてログインするように設定します。

同時に、サーバープロパティは次の図に従って設定されます。

2.次の手順に従って、SQLSERVER構成管理ツール-> TCP / IP-> IPアドレスを入力し、IPアドレスを127.0.0.1に、ポートを1433に変更します。

おすすめ

転載: blog.csdn.net/fanxiaoduo1/article/details/106296621
おすすめ